Java: Stack Traces

A stack trace is the list of methods that the program was in the middle of when the stack trace was printed. It's typically printed to the console when an unexpected error occurs (an exception is thrown but never caught). A stack trace is very useful for debugging: not only do you see where the error happened, but also how the program arrived in this place.

Example

Exception in thread "main" java.lang.NumberFormatException: For input string: "3.1415"
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
    at java.lang.Integer.parseInt(Integer.java:580)
    at ExampleCli.parseNumericArgument(ExampleCli.java:47)
    at ExampleCli.parseCliOptions(ExampleCli.java:27)
    at ExampleCli.main(ExampleCli.java:11)

The stack trace can be read from the bottom up:

The trailing (ExampleCli.java:11) part tells the source file and line number of the method call.

Caused By

A stack trace may have "caused by" sections. An exception in the database layer could for instance be the cause for an exception in the service layer.

See Java: Chained Exceptions.

Suppressed Exceptions

A stack trace may include suppressed exceptions. In rare circumstances two or more exceptions may be created separately. Since Java only allows for one exception to propagate, the other exceptions are suppressed.

See Java: Suppressed Exceptions.

Print a stack trace

Use Thread.dumpStack to print a stacktrace without throwing an exception.

You can also examine the current stack trace programatically by calling Thread.getStackTrace which returns an array of StackTraceElement.

Comments

Be the first to comment!