Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting full string stack trace including inner exception

Java's e.printStackTrace() doesn't print all the details of the inner exception's stack trace.

Is there a ready way to generate the complete stack trace in string form? (besides formatting it myself)

Edit

I just found out what printStackTrace() does - apparently the stack frames it filters out are exactly the ones common to the inner exception and the outer one. So in fact it is rather what I want, and not the 'full' stack trace.

like image 447
ripper234 Avatar asked Aug 18 '09 09:08

ripper234


People also ask

How do I get full stack trace of exception?

By default, the stack trace is captured immediately before an exception object is thrown. Use StackTrace to get stack trace information when no exception is being thrown.

Does exception toString include inner exception?

The default implementation of ToString obtains the name of the class that threw the current exception, the message, the result of calling ToString on the inner exception, and the result of calling Environment.


2 Answers

I suggest that you use the ExceptionUtils class from Apache Commons lang, which provides useful method for that.

like image 165
Romain Linsolas Avatar answered Sep 22 '22 01:09

Romain Linsolas


I ended up rolling my own (I took the implementation of Throwable.printStackTrace() and tweaked it a bit):

public static String joinStackTrace(Throwable e) {
    StringWriter writer = null;
    try {
        writer = new StringWriter();
        joinStackTrace(e, writer);
        return writer.toString();
    }
    finally {
        if (writer != null)
            try {
                writer.close();
            } catch (IOException e1) {
                // ignore
            }
    }
}

public static void joinStackTrace(Throwable e, StringWriter writer) {
    PrintWriter printer = null;
    try {
        printer = new PrintWriter(writer);

        while (e != null) {

            printer.println(e);
            StackTraceElement[] trace = e.getStackTrace();
            for (int i = 0; i < trace.length; i++)
                printer.println("\tat " + trace[i]);

            e = e.getCause();
            if (e != null)
                printer.println("Caused by:\r\n");
        }
    }
    finally {
        if (printer != null)
            printer.close();
    }
}
like image 29
ripper234 Avatar answered Sep 24 '22 01:09

ripper234