Inspects the Throwable to obtain the root cause. - Java java.lang

Java examples for java.lang:Throwable

Description

Inspects the Throwable to obtain the root cause.

Demo Code

/*// w w  w .  j  av  a2 s. c o m
 * Copyright 2011-2016 UnboundID Corp.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License (GPLv2 only)
 * or the terms of the GNU Lesser General Public License (LGPLv2.1 only)
 * as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, see <http://www.gnu.org/licenses>.
 */
//package com.java2s;
import java.util.ArrayList;

import java.util.List;

public class Main {
    /**
     * Inspects the Throwable to obtain the root cause. This method walks through
     * the exception chain to the last element (the "root" of the tree) and
     * returns that exception.
     * <p>
     * This method handles recursive <code>cause</code> structures that
     * might otherwise cause infinite loops. If the Throwable parameter has a
     * <code>cause</code> of itself, then a reference to itself will be returned.
     * If the <code>cause</code> chain loops, the last element in the chain before
     * it loops is returned.
     *
     * @param t the Throwable to get the root cause for. This may be null.
     * @return the root cause of the Throwable, or null if none is found or the
     *         input is null.
     */
    public static Throwable getRootCause(final Throwable t) {
        if (t == null) {
            return null;
        }

        List<Throwable> chain = new ArrayList<Throwable>(10);
        Throwable current = t;
        while (current != null && !chain.contains(current)) {
            chain.add(current);
            current = current.getCause();
        }

        if (chain.size() < 2) {
            return t;
        } else {
            return chain.get(chain.size() - 1);
        }
    }
}

Related Tutorials