Java Dump Throwable dumpThrowable(final String additionalDescr, final Throwable t)

Here you can find the source of dumpThrowable(final String additionalDescr, final Throwable t)

Description

Dumps a Throwable in a decorating message including the current thread name, and its #dumpStack(PrintStream,StackTraceElement[],int,int) stack trace .

License

Open Source License

Declaration

public static void dumpThrowable(final String additionalDescr, final Throwable t) 

Method Source Code


//package com.java2s;
import java.io.PrintStream;

public class Main {
    /**/*from  w w  w.  java 2  s.  c  om*/
     * Dumps a {@link Throwable} in a decorating message including the current thread name,
     * and its {@link #dumpStack(PrintStream, StackTraceElement[], int, int) stack trace}.
     * <p>
     * Implementation will iterate through all {@link Throwable#getCause() causes}.
     * </p>
     */
    public static void dumpThrowable(final String additionalDescr, final Throwable t) {
        System.err.println("Caught " + additionalDescr + " " + t.getClass().getSimpleName() + ": " + t.getMessage()
                + " on thread " + Thread.currentThread().getName());
        dumpStack(System.err, t.getStackTrace(), 0, -1);
        int causeDepth = 1;
        for (Throwable cause = t.getCause(); null != cause; cause = cause.getCause()) {
            System.err.println("Caused[" + causeDepth + "] by " + cause.getClass().getSimpleName() + ": "
                    + cause.getMessage() + " on thread " + Thread.currentThread().getName());
            dumpStack(System.err, cause.getStackTrace(), 0, -1);
            causeDepth++;
        }
    }

    public static void dumpStack(final PrintStream out) {
        dumpStack(out, 1, -1);
    }

    public static void dumpStack(final PrintStream out, final int skip, final int depth) {
        dumpStack(out, new Exception(""), skip + 1, depth);
    }

    public static void dumpStack(final PrintStream out, final Throwable t, final int skip, final int depth) {
        dumpStack(out, t.getStackTrace(), skip, depth);
    }

    public static void dumpStack(final PrintStream out, final StackTraceElement[] stack, final int skip,
            final int depth) {
        if (null == stack) {
            return;
        }
        final int maxDepth;
        if (0 > depth) {
            maxDepth = stack.length;
        } else {
            maxDepth = Math.min(depth + skip, stack.length);
        }
        for (int i = skip; i < maxDepth; i++) {
            out.println("    [" + i + "]: " + stack[i]);
        }
    }
}

Related

  1. dump(final Throwable throwable)
  2. dumpThrowable(Throwable e)
  3. dumpThrowable(Throwable thr)