EMZETT.
Login

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:

MessageCauseRemedy
NullPointerExceptionReference is nullWhere is the variable set? Check for null, use Optional
ArrayIndexOutOfBoundsExceptionIndex outside 0 … length-1Check loop bounds
ClassCastExceptionWrong castCheck instanceof, use generics
NumberFormatExceptionText is not a numberValidate / catch input
ClassNotFoundException, NoClassDefFoundErrorClass not on the classpathCheck dependency/path
StackOverflowErrorEndless recursionCheck termination condition
OutOfMemoryErrorHeap full or memory leakRaise -Xmx, analyze heap dump
cannot find symbol (compiler)Typo, missing importCheck spelling, import
UnsupportedClassVersionErrorBytecode newer than the JREAlign 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 diff and git bisect find 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