Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

Throwable.printStackTrace()

Prints the exception and the chain of calls that led to it to the error stream.

Available since: Java 1.0

Syntax

public void printStackTrace()

Examples

The stack trace shows where the error happened:

int parse(String s) {
    return Integer.parseInt(s);
}
 
void main() {
    try {
        parse("abc");
    } catch (NumberFormatException e) {
        e.printStackTrace();
    }
    IO.println("done");
}

Output:

java.lang.NumberFormatException: For input string: "abc"
	at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:67)
	at java.base/java.lang.Integer.parseInt(Integer.java:565)
	at java.base/java.lang.Integer.parseInt(Integer.java:662)
	at Main.parse(Main.java:2)
	at Main.main(Main.java:7)
done

Notes

Read the trace from top to bottom: the first line is the type and message, then come the methods from the error location down to main, with the file and line number. This output is from a compiled program; when launched as a single file (java Main.java) a few more launcher lines appear at the end. The output goes to System.err. Real applications pass the exception to a logger instead of calling this method.

See also

Related recipes

In the tutorial

  • try, catch and finally — Handling exceptions in Java — the try and catch blocks, several catch blocks, multi-catch, finally and throwing exceptions with throw.

Thanks for reading!

Donate to the site — we work hard for you.