Skip to lesson

Read a stack trace with Caused by

A stack trace is the report Java prints when an exception is not caught: what went wrong, and the exact chain of method calls that led there. Long traces look scary, but they follow a fixed pattern, and you rarely need more than three lines of one.

Exception line, message and at frames

A stack trace is the list of method calls that were running when an exception was created, printed from the line where it happened down to main.

A stack trace starts with the exception line: the full class name and message, such as java.lang.ArithmeticException: / by zero. Every line below it is a frame, at ClassName.methodName(FileName.java:line): one method that was running.

Example 1 · A first stack trace

FirstTraceDemo.javaJava
public class FirstTraceDemo {    static int average(int total, int count) {        return total / count;    }
    static void printReport(String subject, int total, int count) {        int avg = average(total, count);        System.out.println(subject + " average: " + avg);    }
    public static void main(String[] args) {        printReport("Maths", 2460, 30);        printReport("Physics", 0, 0);        System.out.println("Report done");    }}
Sample output
Maths average: 82
Exception in thread "main" java.lang.ArithmeticException: / by zero
	at FirstTraceDemo.average(FirstTraceDemo.java:3)
	at FirstTraceDemo.printReport(FirstTraceDemo.java:7)
	at FirstTraceDemo.main(FirstTraceDemo.java:13)

What this code does

  • The exception line names ArithmeticException and its message / by zero. The top frame says it was thrown in average, at line 3 of FirstTraceDemo.java.
  • Reading down: average was called by printReport at line 7, which was called by main at line 13, the Physics call. Report done never prints because nothing caught the exception.

For an uncaught exception the first line starts with Exception in thread "main", the name of the thread that failed. Every line below it is a frame: at ClassName.methodName(FileName.java:line). Each frame is one method that was running at that moment. The top frame is where the exception was thrown; the frame below it is the method that called that one, and so on, down to main at the bottom.

So you read a trace top to bottom as "where it broke", then "who called it", back to where the program started.

Finding the first line from your own code

When the exception comes from inside the JDK, the top frames are not yours. Lines that start with java.base/ belong to Java's own library, such as Integer.parseInt. That code is almost never the bug; it is reporting that you gave it a bad value.

Example 2 · Skip the java.base lines

OwnLineDemo.javaJava
import java.util.List;
public class OwnLineDemo {    static int parseMarks(String row) {        String[] parts = row.split(",");        return Integer.parseInt(parts[1].trim());    }
    static int total(List<String> rows) {        int sum = 0;        for (String row : rows) {            sum += parseMarks(row);        }        return sum;    }
    public static void main(String[] args) {        List<String> rows = List.of("Asha, 81", "Ravi, 7x", "Meena, 90");        System.out.println("Total: " + total(rows));    }}
Sample output
Exception in thread "main" java.lang.NumberFormatException: For input string: "7x"
	at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:67)
	at java.base/java.lang.Integer.parseInt(Integer.java:662)
	at java.base/java.lang.Integer.parseInt(Integer.java:778)
	at OwnLineDemo.parseMarks(OwnLineDemo.java:6)
	at OwnLineDemo.total(OwnLineDemo.java:12)
	at OwnLineDemo.main(OwnLineDemo.java:19)

What this code does

  • The first three frames start with java.base/: they are inside Integer.parseInt, which only reports the bad text "7x".
  • The first frame from your own code is OwnLineDemo.parseMarks(OwnLineDemo.java:6), the line that passed the text to parseInt. That is where to look; the frames below it show it was called from total and main.

So skip down to the first frame from your own code: the first at line with one of your class names. That line is where your program passed the bad value or did the wrong thing. Open that file at that line number first.

Line numbers in java.base/ frames depend on your Java version, so they can differ from the ones shown here. Your own line numbers stay the same.

Caused by sections and their order

A chained exception prints one block per exception. The outer exception comes first, then a Caused by: block for its cause, then another for the cause's cause, and so on. The order is from the outer, general message down to the specific one.

Example 3 · A chain printed with Caused by

CausedByDemo.javaJava
class ReportException extends Exception {    ReportException(String message, Throwable cause) {        super(message, cause);    }}
public class CausedByDemo {    static void validate(int marks) {        if (marks < 0 || marks > 100) {            throw new IllegalArgumentException("marks must be 0 to 100, got " + marks);        }    }
    static void loadRow(String name, int marks) throws ReportException {        try {            validate(marks);        } catch (IllegalArgumentException e) {            throw new ReportException("bad row for " + name, e);        }    }
    static void buildReport() {        try {            loadRow("Asha", 81);            loadRow("Ravi", 105);        } catch (ReportException e) {            throw new IllegalStateException("class report failed", e);        }    }
    public static void main(String[] args) {        try {            buildReport();        } catch (IllegalStateException e) {            e.printStackTrace(System.out);        }    }}
Output
java.lang.IllegalStateException: class report failed
	at CausedByDemo.buildReport(CausedByDemo.java:27)
	at CausedByDemo.main(CausedByDemo.java:33)
Caused by: ReportException: bad row for Ravi
	at CausedByDemo.loadRow(CausedByDemo.java:18)
	at CausedByDemo.buildReport(CausedByDemo.java:25)
	... 1 more
Caused by: java.lang.IllegalArgumentException: marks must be 0 to 100, got 105
	at CausedByDemo.validate(CausedByDemo.java:10)
	at CausedByDemo.loadRow(CausedByDemo.java:16)
	... 2 more

What this code does

  • Three blocks, outer first: IllegalStateException (report), Caused by: ReportException (row), Caused by: IllegalArgumentException (marks). The last block is the root cause: Ravi's marks are 105.
  • The root cause's top frame, validate at line 10, is where the bad value was found; its next frame, loadRow at line 16, is the call with Ravi's data. printStackTrace(System.out) is used here so the trace prints in order with normal output.

So the root cause is the last Caused by: block. In a long trace from a real project, jump to the last Caused by:, read its message, and then find its first frame from your own code.

What '... 2 more' means

Under a Caused by: block you often see a line like ... 2 more. It means the last 2 frames of this exception are exactly the same as the last 2 frames of the exception printed above it, so Java does not print them twice.

Example 4 · Counting the hidden frames

MoreFramesDemo.javaJava
public class MoreFramesDemo {    static void checkSeat(int seat) {        throw new IllegalArgumentException("seat number " + seat + " is not valid");    }
    static void bookSeat(int seat) {        try {            checkSeat(seat);        } catch (IllegalArgumentException e) {            throw new IllegalStateException("booking failed", e);        }    }
    static void bookTicket(int seat) {        bookSeat(seat);    }
    public static void main(String[] args) {        try {            bookTicket(0);        } catch (IllegalStateException e) {            e.printStackTrace(System.out);            System.out.println("---");            System.out.println("outer frames: " + e.getStackTrace().length);            System.out.println("cause frames: " + e.getCause().getStackTrace().length);            for (StackTraceElement frame : e.getCause().getStackTrace()) {                System.out.println("  cause frame: " + frame.getMethodName() + " line " + frame.getLineNumber());            }        }    }}
Output
java.lang.IllegalStateException: booking failed
	at MoreFramesDemo.bookSeat(MoreFramesDemo.java:10)
	at MoreFramesDemo.bookTicket(MoreFramesDemo.java:15)
	at MoreFramesDemo.main(MoreFramesDemo.java:20)
Caused by: java.lang.IllegalArgumentException: seat number 0 is not valid
	at MoreFramesDemo.checkSeat(MoreFramesDemo.java:3)
	at MoreFramesDemo.bookSeat(MoreFramesDemo.java:8)
	... 2 more
---
outer frames: 3
cause frames: 4
  cause frame: checkSeat line 3
  cause frame: bookSeat line 8
  cause frame: bookTicket line 15
  cause frame: main line 20

What this code does

  • The cause really has 4 frames, but only 2 are printed. Its last two, bookTicket and main, are the same as the last two of the outer exception, so Java prints ... 2 more instead.
  • getStackTrace() returns the frames as an array of StackTraceElement, with methods such as getMethodName() and getLineNumber(). The printed trace is built from exactly these values.

Those hidden frames are the callers both exceptions share, usually the path from main down to the method that did the wrapping. If you need them, read them in the block above. The useful part, where the cause differs, is always printed in full.

Next step

Check your understanding

12 quick questions