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.


Exception in thread "main" java.lang.NumberFormatException: For input string: "3.1415"
    at java.lang.NumberFormatException.forInputString(
    at java.lang.Integer.parseInt(
    at ExampleCli.parseNumericArgument(
    at ExampleCli.parseCliOptions(
    at ExampleCli.main(

The stack trace can be read from the bottom up:

The trailing ( 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.


Be the first to comment!