Search This Blog

Monday 4 June 2012

print java stack trace

this is a Java static method that prints on the System.out the stack trace of a Throwable object. It goes recursively through the chain of Throwable objects, printing also the causing objects.

public static void printStackTrace(Throwable th) {
    for (StackTraceElement ste : th.getStackTrace()) {
      System.out.println("file " + ste.getFileName() + ", method " + ste.getMethodName() + ", line "
          + ste.getLineNumber() + ", " + th.getMessage());
    }
    if (th.getCause() != null) {
      System.out.println("... cause ...");
      printStackTrace(th.getCause());
    }
  }