views:

1204

answers:

4

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.

+3  A: 

I suggest that you use the ExceptionUtils class from Apache Commons lang, which provides useful method for that, such as getFullStacktrace().

romaintaz
Actually, getFullStacktrace() still doesn't print the inner stack trace.
ripper234
Unfortunately, there are no printFullStacktrace() method, but you can do System.err.println(getFullStacktrace());
romaintaz
+1  A: 

Yes you can use the StackTraceElement class returned by Throwable.getStackTrace() and find the details.

From the API:

The last element of the array (assuming the array's length is non-zero) represents the bottom of the stack, which is the first method invocation in the sequence.

techzen
How is this not 'formatting it myself' ?
ripper234
yes, this option does not address the formatting part.
techzen
A: 

getCause() method.

try
 {
    ....
  }catch(Exception ex) {
     Throwable t=ex;
    do{
        t.printStackTrace() 
        t=t.getCause();

       }while(t!=null);  
  }
adatapost
getMessage doesn't print a stack trace.
ripper234
Thanks for your kind suggestion
adatapost
+1  A: 

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();
    }
}
ripper234