Utility method to get cause of exception. - Java java.lang

Java examples for java.lang:Throwable

Description

Utility method to get cause of exception.

Demo Code

/*//w  w w  .  jav  a  2s  .  c o m
 * Copyright 1997-2004 The Apache Software Foundation
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *     http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.reflect.Method;
import java.util.StringTokenizer;

public class Main{
    private static final String GET_CAUSE_NAME = "getCause";
    private static final Class[] GET_CAUSE_PARAMTYPES = new Class[0];
    /**
     * Utility method to get cause of exception.
     * @param throwable a <code>Throwable</code>
     * @param useReflection if <code>true</code> will use reflection to handle JDK1.4
     *                      nested exceptions
     * @return cause of specified exception
     */
    public static Throwable getCause(final Throwable throwable,
            final boolean useReflection) {
        if (throwable instanceof CascadingThrowable) {
            final CascadingThrowable cascadingThrowable = (CascadingThrowable) throwable;
            return cascadingThrowable.getCause();
        } else if (useReflection) {
            try {
                final Class clazz = throwable.getClass();
                final Method method = clazz.getMethod(GET_CAUSE_NAME,
                        GET_CAUSE_PARAMTYPES);
                return (Throwable) method.invoke(throwable, null);
            } catch (final Throwable t) {
                return null;
            }
        } else {
            return null;
        }
    }
}

Related Tutorials