Java's most common exceptions and what they mean
NullPointerException, ClassCastException, StackOverflowError, and reading a stack trace under pressure.
Adetayo Akinsanya2026-09-088 min read
- Java
- Core Java
- Exceptions
- Debugging

Part 15 of the series.Read How Java separates interface from implementation (Part 13) first if you have not.
In this article (8 sections)
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "String.toUpperCase()" because "name" is null
at com.example.UserService.formatName(UserService.java:24)
at com.example.UserService.greet(UserService.java:18)
at com.example.Main.main(Main.java:10)
You will read stack traces like this more than any other Java output. The class name tells you what happened. The message tells you which reference was null. The frames tell you exactly where.
Knowing what each exception type means lets you find the bug without reading every line of the program. This article covers the six you will encounter most often.
How to read the stack trace
Each indented line is one frame in the call stack at the moment the exception was thrown. The first frame is the site of the throw. The last frame is where the thread started, usually main.
java.lang.NullPointerException: Cannot invoke "String.toUpperCase()" because "name" is null
at com.example.UserService.formatName(UserService.java:24)
at com.example.UserService.greet(UserService.java:18)
at com.example.Main.main(Main.java:10)
Start from the top. UserService.java:24 is the line that threw. Open that file, go to line 24. If the class is yours, that is where you look first. If the top frame is inside a library class you did not write, move to the second frame, which is your code calling into that library.
The exception message refines the type. NullPointerException alone tells you something was null. The message “Cannot invoke String.toUpperCase() because name is null” tells you which variable was null and what you tried to do with it. Java 14 introduced helpful NullPointerException messages (JEP 358); on earlier versions you get just the type with no message.
A “Caused by:” section means the exception was wrapped:
Exception in thread "main" com.example.DataAccessException: Failed to load user 42
at com.example.UserRepository.findById(UserRepository.java:31)
at com.example.UserService.getUser(UserService.java:19)
at com.example.Main.main(Main.java:12)
Caused by: java.io.FileNotFoundException: /data/users/42.json (No such file or directory)
at java.base/java.io.FileInputStream.open0(Native Method)
at java.base/java.io.FileInputStream.open(FileInputStream.java:216)
at java.base/java.io.FileInputStream.<init>(FileInputStream.java:157)
...
The DataAccessException is the outer exception. The FileNotFoundException is the cause, which is what actually failed. Read the “Caused by” chain from bottom to top: the original failure first, then each layer that caught and re-threw it.
NullPointerException
A reference variable holds an address. null means the variable holds no address. Calling a method or accessing a field on null throws NullPointerException because there is no object at the end of a null to operate on.
String name = null;
System.out.println(name.length()); // NullPointerException
The five common sources:
1. A method returned null and you used the result without checking.
String value = map.get("missingKey"); // returns null
System.out.println(value.trim()); // NPE
2. A field was never initialized.
public class Order {
private List<Item> items; // null until initialized
public int total() {
return items.stream().mapToInt(Item::price).sum(); // NPE
}
}
3. An array element was never assigned.
String[] names = new String[3]; // all elements null
System.out.println(names[0].length()); // NPE
4. Autoboxing a null Integer to int.
Integer count = null;
int n = count; // NullPointerException during unboxing
5. A parameter that the caller expected to be non-null.
The fix depends on the cause. If a method can legitimately return null, check before using the result. If it should never return null, that is a bug in that method. Optional<T> signals “this might be absent” in the return type, which forces the caller to handle the absent case explicitly rather than getting a surprise NPE at runtime.
ArrayIndexOutOfBoundsException
An array of length n has valid indices 0 through n - 1. Accessing index n or any negative index throws ArrayIndexOutOfBoundsException.
int[] scores = {90, 85, 72};
System.out.println(scores[3]); // length is 3, valid indices are 0, 1, 2
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
The message gives both the index you used and the array’s length. If the index equals the length, you are off by one. Check the loop condition: i < scores.length, not i <= scores.length.
The same error class applies to multi-dimensional arrays; each dimension is a separate array, so accessing matrix[2][4] can fail on either dimension independently.
ClassCastException
When you cast a reference to a type that the object is not an instance of, the JVM throws ClassCastException.
Object value = "hello";
Integer number = (Integer) value; // ClassCastException
Exception in thread "main" java.lang.ClassCastException: class java.lang.String cannot be cast to class java.lang.Integer
The message names both the actual class and the class you tried to cast to. That pairing tells you exactly which cast failed. Look at the top frame to find the line.
The safe way to cast is to check first with instanceof, or use pattern matching (Java 16+):
// Before Java 16
if (value instanceof Integer) {
Integer number = (Integer) value;
System.out.println(number * 2);
}
// Java 16+ pattern matching
if (value instanceof Integer number) {
System.out.println(number * 2);
}
Pattern matching eliminates the double lookup: the check and the cast happen in one operation, and the variable number is in scope and correctly typed inside the if block.
ClassCastException appears frequently when working with raw collections (pre-generics, or when using external data like JSON), when unmarshalling heterogeneous data structures, and in legacy code that uses Object where a typed container would now serve better.
IllegalArgumentException
IllegalArgumentException is an unchecked exception that signals the caller passed an invalid argument. It indicates a programming error on the caller’s side.
public static double sqrt(double n) {
if (n < 0) {
throw new IllegalArgumentException("Cannot take sqrt of negative: " + n);
}
return Math.sqrt(n);
}
The convention: throw it early, before doing any work, so the message points directly to the bad input. The message should include the invalid value, not just describe the constraint. “n must be non-negative (was -4.0)” is more useful than “invalid argument”.
A related type is IllegalStateException, which signals that the method was called at the wrong time, not that the argument was wrong. Calling iterator.remove() before calling iterator.next() is an illegal state, not an illegal argument.
StackOverflowError
Every method call pushes a frame onto the call stack. The JVM limits the stack size (the default on HotSpot is roughly 512KB to 1MB per thread, depending on the platform; -Xss controls it). When the stack fills, the JVM throws StackOverflowError.
public static int factorial(int n) {
return n * factorial(n - 1); // no base case
}
Exception in thread "main" java.lang.StackOverflowError
at com.example.Main.factorial(Main.java:5)
at com.example.Main.factorial(Main.java:5)
at com.example.Main.factorial(Main.java:5)
... (hundreds more identical frames)
The repeated identical frame is the tell. It is almost always a missing or unreachable base case in a recursive method.
StackOverflowError is an Error, not an Exception. Do not catch it and continue. The stack is in an unrecoverable state once the error fires. Fix the recursion instead.
Mutual recursion is the less obvious variant: methodA calls methodB, which calls methodA, which calls methodB. The same repeated frames will appear, alternating between the two methods.
IOException
IOException is the checked base class for I/O failures. It signals conditions that your code cannot prevent: a file that does not exist, a network that dropped, a disk that is full.
try {
String content = Files.readString(Path.of("/data/config.json"));
} catch (IOException e) {
System.err.println("Could not read config: " + e.getMessage());
}
The two most common subclasses:
FileNotFoundException means the file path you provided does not point to an existing file. Check the path: a relative path resolves against the working directory of the Java process, which may not be where you expect when running from an IDE.
SocketTimeoutException means a network operation waited longer than the configured timeout. The connection worked, but reading the response took too long. The timeout is a property of the socket or HTTP client configuration, not the exception type itself.
Since IOException is checked, the compiler forces you to handle it. That is intentional: file and network operations fail. Code that ignores the failure leaves the caller with no idea why subsequent operations produce garbage results.
Prediction exercise
public static int sum(List<Integer> values) {
int total = 0;
for (Integer v : values) {
total += v; // unboxing
}
return total;
}
List<Integer> withNull = new ArrayList<>();
withNull.add(10);
withNull.add(null);
withNull.add(5);
System.out.println(sum(withNull));
Which exception is thrown, and on which iteration? Then: what changes if you replace List<Integer> with int[]? The next article covers how to design your own exception types, when to use try-with-resources, and how to chain exceptions so the original cause is never lost. Exception design: try-with-resources, chaining, and custom types picks up from here.
Questions or corrections
Found a mistake or have a question about this breakdown? Reach out directly.