returns a list of all throwable (including the one you passed in) wrapped by the given throwable. - Java java.lang

Java examples for java.lang:Throwable

Description

returns a list of all throwable (including the one you passed in) wrapped by the given throwable.

Demo Code


//package com.java2s;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

public class Main {
    /**/* w  w  w .  j  a  v a  2s . c  o m*/
     * returns a list of all throwables (including the one you passed in)
     * wrapped by the given throwable. In contrast to a simple call to
     * getClause() on each throwable it will also check if the throwable class
     * contain a method getRootCause() (e.g. ServletException or JspException)
     * and call it instead. The first list element will your passed in
     * exception, the last list element is the cause.
     * 
     * @param cause
     * @return
     */
    public static List<Throwable> getExceptions(Throwable cause) {
        List<Throwable> exceptions = new ArrayList<Throwable>(10);
        exceptions.add(cause);

        do {
            Throwable nextCause;
            try {
                Method rootCause = cause.getClass().getMethod(
                        "getRootCause", new Class[] {});
                nextCause = (Throwable) rootCause.invoke(cause,
                        new Object[] {});
            } catch (Exception e) {
                nextCause = cause.getCause();
            }
            if (cause == nextCause) {
                break;
            }

            if (nextCause != null) {
                exceptions.add(nextCause);
            }

            cause = nextCause;
        } while (cause != null);

        return exceptions;
    }
}

Related Tutorials