Return the last throwable in the chain. - Java java.lang

Java examples for java.lang:Throwable

Description

Return the last throwable in the chain.

Demo Code

/*//from w w w. j  a  v  a  2s.  co m
 * Copyright 2004 Stephen J. McConnell.
 *
 * 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.
 */
//package com.java2s;

import java.lang.reflect.Method;

public class Main {
    /**
     * Return the last throwable in the chain.
     * @param exception the exception to extract the last throwable from
     * @return the initiating cause
     */
    private static Throwable getLastThrowable(Throwable exception) {
        Throwable cause = getCause(exception);
        if (cause != null) {
            return getLastThrowable(cause);
        } else {
            return exception;
        }
    }

    /**
     * Get a causal exception using reflection.
     * @param exception the exception
     * @return the causal exception
     */
    private static Throwable getCause(Throwable exception) {
        if (null == exception) {
            return null;
        }

        try {
            Class clazz = exception.getClass();
            Method method = clazz.getMethod("getCause", new Class[0]);
            return (Throwable) method.invoke(exception, new Object[0]);
        } catch (Throwable e) {
            return null;
        }
    }
}

Related Tutorials