Troubleshooting in Java
In short: Troubleshooting means systematic bug hunting. In Java you first read the error message with its stack trace, narrow down the place, and check assumptions with prints, a debugger or tests.
In more detail: Most errors give themselves away: the stack trace names the exception, the message and the call chain with file and line. Whoever can read it solves a large part of problems within minutes.
In Depth
1. Read the error message (top to bottom):
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "String.length()" because "name" is null
at Person.length(Person.java:12)
at Main.main(Main.java:5)
Top: type and reason of the exception. Below: the first line is where it blew up. The others show who called it. Look for your first own line, not those in libraries.
2. Typical cases:
| Message | Cause | Remedy |
|---|---|---|
NullPointerException | Reference is null | Where is the variable set? Check for null, use Optional |
ArrayIndexOutOfBoundsException | Index outside 0 … length-1 | Check loop bounds |
ClassCastException | Wrong cast | Check instanceof, use generics |
NumberFormatException | Text is not a number | Validate / catch input |
ClassNotFoundException, NoClassDefFoundError | Class not on the classpath | Check dependency/path |
StackOverflowError | Endless recursion | Check termination condition |
OutOfMemoryError | Heap full or memory leak | Raise -Xmx, analyze heap dump |
cannot find symbol (compiler) | Typo, missing import | Check spelling, import |
UnsupportedClassVersionError | Bytecode newer than the JRE | Align Java versions |
3. Approach:
- Reproduce: Only when the error appears on demand can it be fixed reliably.
- Narrow down: Print variables or set breakpoints in the debugger and step through line by line. Bisection: is the error before or after this spot?
- Only one change at a time, then test.
- Suspect recent changes:
git diffandgit bisectfind the trigger. - Tools: IDE debugger,
jstack(thread dump for hangs),jmap/heap dump and VisualVM (memory), logging. - Secure it: Turn every found bug into a unit test so it does not return.
- Rubber-duck debugging: Explaining the problem aloud (to a rubber duck) often exposes the flaw in thinking.
See also: Exceptions, Debugging, Error codes