How to Read a Java Stack Trace and Fix the Error

admin5 min read
In this tutorial
  1. A first example
  2. Reading it line by line
  3. Finding your code in a long trace
  4. Caused by: finding the root cause
  5. The five exceptions beginners hit most
  6. A debugging routine that works
  7. Printing stack traces properly
  8. Summary

A wall of red text in your console can be intimidating, especially when you are new to Java. The good news: a stack trace is not noise. It is Java telling you exactly what went wrong and where. Once you know how to read one, most bugs take minutes instead of hours to fix.

A first example

public class OrderService {
    static class Customer {
        String email;
    }

    static String emailDomain(Customer c) {
        return c.email.substring(c.email.indexOf('@') + 1);
    }

    public static void main(String[] args) {
        Customer guest = new Customer();   // email never set, so it is null
        System.out.println(emailDomain(guest));
    }
}

Running this prints something like:

Exception in thread "main" java.lang.NullPointerException: Cannot invoke "String.indexOf(int)" because "c.email" is null
    at OrderService.emailDomain(OrderService.java:7)
    at OrderService.main(OrderService.java:12)

Reading it line by line

Line 1: the exception type and message.

  • java.lang.NullPointerException is the type of problem.
  • The text after the colon is the message. Since Java 14, NullPointerException messages are “helpful”: they tell you exactly which expression was null, here c.email. (If you compile without debug information, you may see <parameter1>.email instead. IDEs and Maven include it by default.)

The “at” lines: the call stack.

Each line is one method call, with the most recent call at the top:

  • at OrderService.emailDomain(OrderService.java:7): the exception happened in emailDomain, at line 7 of OrderService.java.
  • at OrderService.main(OrderService.java:12): emailDomain was called from main, at line 12.

So the story, read from the bottom up, is: main (line 12) called emailDomain, which crashed at line 7 because c.email was null.

In an IDE such as IntelliJ, these file names and line numbers are clickable and take you straight to the line.

Finding your code in a long trace

Real applications produce traces with dozens of lines from frameworks such as Spring, Hibernate or Tomcat. The trick is to scan from the top for the first line in your own package:

java.lang.IllegalArgumentException: Amount must be positive, got -500.0
    at com.kooredev.bank.Account.withdraw(Account.java:31)
    at com.kooredev.bank.TransferService.transfer(TransferService.java:18)
    at com.kooredev.bank.TransferController.post(TransferController.java:42)
    at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:103)
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:255)
    ... 48 more

The first three lines are yours, and they show the path: the controller called the service, which called withdraw with a negative amount. The framework lines below them show how the request arrived, which you can usually ignore.

Caused by: finding the root cause

Exceptions are often wrapped in other exceptions. The trace then contains one or more Caused by: sections:

Exception in thread "main" java.lang.RuntimeException: Could not load settings
    at com.kooredev.app.Settings.load(Settings.java:22)
    at com.kooredev.app.Main.main(Main.java:9)
Caused by: java.nio.file.NoSuchFileException: config/app.properties
    at java.base/sun.nio.fs.UnixException.translateToIOException(UnixException.java:92)
    at java.base/java.nio.file.Files.newBufferedReader(Files.java:2922)
    at com.kooredev.app.Settings.load(Settings.java:19)
    ... 1 more

The top exception tells you what the program was trying to do (“load settings”); the last Caused by tells you why it failed (the file does not exist). Always scroll down to the last Caused by first: that is usually the real problem.

“… 1 more” just means the remaining lines are identical to the ones in the exception above, so Java does not repeat them.

The five exceptions beginners hit most

1. NullPointerException

You called a method or accessed a field on a reference that is null.

Fix: find out why the value is null (the helpful message tells you which one). Initialise it, check for null before using it, or make sure it can never be null by setting it in the constructor:

String domain = (c.email == null) ? "unknown" : c.email.substring(c.email.indexOf('@') + 1);

For values that may legitimately be missing, consider returning Optional instead of null.

2. ArrayIndexOutOfBoundsException / IndexOutOfBoundsException

java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3

You accessed index 3 of an array whose valid indexes are 0, 1 and 2. Usually a loop uses <= instead of <. Check the loop condition.

3. NumberFormatException

java.lang.NumberFormatException: For input string: "12a"

Integer.parseInt received text that is not a number. Validate input first, or catch the exception and show the user a friendly message. Watch out for hidden spaces: call trim() first.

4. ClassCastException

java.lang.ClassCastException: class java.lang.Integer cannot be cast to class java.lang.String

You cast an object to a type it is not. Use generics so the compiler catches this, or check with instanceof before casting:

if (value instanceof String s) {
    System.out.println(s.toUpperCase());
}

5. ConcurrentModificationException

You modified a collection while looping over it with an enhanced for loop. Use removeIf, or loop with an explicit Iterator and call iterator.remove().

A debugging routine that works

  1. Read the first line: what type of exception, and what does the message say?
  2. Find the first line from your code and open that file at that line number.
  3. Scroll to the last “Caused by” if there is one.
  4. Ask “what value was unexpected?” Add a log statement or set a breakpoint on that line and run in debug mode to inspect variables.
  5. Reproduce it with the smallest possible input, then fix the cause, not the symptom. Wrapping the line in try/catch to make the error disappear is not a fix.

Printing stack traces properly

When you catch an exception, log it with the exception object so the trace is not lost:

catch (IOException e) {
    log.error("Failed to import file {}", path, e);   // SLF4J prints the full trace
}

e.printStackTrace() is fine while learning, but real applications should use a logger. Logging only e.getMessage() throws away the most useful part: the stack trace.

Summary

  • The first line gives the exception type and message; helpful NPE messages name the null expression.
  • “at” lines list the call stack, most recent call first. Look for the first line from your own code.
  • The last “Caused by” is usually the root cause.
  • Most beginner errors come from null values, wrong indexes, bad number input, wrong casts and modifying collections mid-loop.

Learn more about handling errors in checked vs unchecked exceptions.

Ask a question or leave a comment

Your email address will not be published. Required fields are marked *