Beginner · Control flow and methods · topic 10 of 60 · 20 min
Reading errors and debugging
Explanation
Errors are information
Beginners fear red text; professionals read it. Every Java error tells you what went wrong and where. Learning to read the five or six most common ones saves hours every week.
Common compile errors
| Message | Usual cause | Fix |
|---|---|---|
| cannot find symbol | A typo in a name, a missing import, or a variable used outside its scope | Check spelling and case; add the import; declare the variable in the right block |
| incompatible types: X cannot be converted to Y | Storing a value of the wrong type (double into int, String into int) | Change the type, cast, or parse |
| missing return statement | A non-void method does not return on every path | Add a final return or an else branch |
| ';' expected / ')' expected | A missing semicolon or bracket, usually on the line BEFORE the caret | Look at the end of the previous line |
| variable might not have been initialized | A local variable read before a value is assigned | Give it an initial value |
| unreachable statement | Code after a return, break or infinite loop | Remove or move the code |
Reading a stack trace
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "String.length()" because "name" is null
at com.shop.Customer.initials(Customer.java:14)
at com.shop.Report.print(Report.java:31)
at com.shop.Main.main(Main.java:9)- Line 1: the exception type and message. Modern Java (14+) prints helpful NullPointerException messages that name the null variable.
- The "at" lines list the calls, newest first. Customer.java line 14 is where it crashed.
- Main.main called Report.print, which called Customer.initials. Go to the first line that is YOUR code (not java.* or a library).
- If there is a "Caused by:" section further down, the root cause is usually the LAST "Caused by".
Common run-time exceptions
- NullPointerException: calling a method on null.
- ArrayIndexOutOfBoundsException: index < 0 or >= length.
- ArithmeticException: integer division by zero.
- NumberFormatException: Integer.parseInt on text that is not a number.
- ClassCastException: casting an object to a class it is not.
- StackOverflowError: recursion without a working base case.
Using the debugger
- Click in the margin next to a line to set a breakpoint (a red dot).
- Start the program in Debug mode (the bug icon in IntelliJ IDEA, VS Code or Eclipse).
- When it pauses, look at the Variables panel; hover over any variable.
- Step Over (run this line), Step Into (go inside the method call), Step Out (finish this method), Resume (run to the next breakpoint).
- Add a watch for an expression like total > 1000 to see it change.
println debugging (printing values at key points) also works and is fine for quick checks, but remember to remove the prints afterwards. Real projects use a logging library (SLF4J with Logback or Log4j 2) instead of System.out.
Need help?
Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.
Try:
Watch the lesson
Reading errors and debugging · 1/6
In this lesson you will learn to read Java errors calmly and find bugs with a debugger.
Prefer a video by a teacher? Find free videos on “java stack trace explained how to debug intellij breakpoints” on YouTube ↗
In real life: A crash in a hospital report
A hospital's nightly report crashed with a NullPointerException. The stack trace pointed to Patient.java line 22, in a method that printed the patient's doctor name. The helpful NPE message said "doctor" was null: walk-in patients have no assigned doctor. The fix was to print "Not assigned" when doctor is null, plus a test for walk-in patients.
String doctorName = (p.getDoctor() == null) ? "Not assigned" : p.getDoctor().getName();Practice (0/3 done)
javac reports "error: cannot find symbol symbol: variable totl". What is the most likely cause?
Stack trace: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5 at Marks.average(Marks.java:8) at Marks.main(Marks.java:3) Where do you look first?
Write a small program with a deliberate bug: a loop for (int i = 0; i <= marks.length; i++) summing an int array. Run it, read the stack trace, then set a breakpoint inside the loop, run in Debug mode, step through and watch i reach marks.length. Fix the bug.
Quick quiz
Read more (free)
Related help
Before this, learn
This topic builds on these. If something here feels new, open them first.
Related topics
- Loops: for, while, do-while and for-eachControl flow and methods · same module
- switch statements and switch expressionsControl flow and methods · same module
- Debugging like a pro: DevTools and VS CodeFrontend Web Development · Async JavaScript, modules and tools
- Debugging and performanceKotlin and Android App Development · Testing Android apps
- Debugging with gdbC Programming (from zero to systems) · Debugging and tools
- Exceptions: try, catch, finally and custom exceptionsC# and .NET · Exceptions, delegates, events and async
Questions people ask about this
Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.
Which error is found by the compiler, before running?
Answer: missing return statement
The others are run-time exceptions/errors.
In a stack trace, which "at" line is the place where the exception happened?
Answer: The first one (top)
The top frame is where it was thrown; lines below are the callers.
Integer.parseInt("12a") throws…
Answer: NumberFormatException
The text is not a valid integer.
What does "Step Into" do in a debugger?
Answer: Goes inside the method called on the current line
Step Into enters the called method.
What does the debugger; statement do?Related
Answer: Pauses the code at that line when DevTools is open
debugger works like a breakpoint written in the code. Without DevTools open it does nothing.
System.out.println("Sum: " + 2 + 3) prints…Related
Answer: Sum: 23
Left to right: "Sum: " + 2 is a String, then + 3 joins "3".
What does a breakpoint do?Related
Answer: Pauses execution at a line so you can inspect values
Run in Debug mode to use it.
Which flag adds debug information for gdb?Related
Pass the quiz (60% or more) or mark this topic as done when you are ready.
Your progress is saved on this device only.
Next steps
- This is the last topic of “Control flow and methods”. The module exam comes next.
- Module 2 exam: Control flow and methods · 12 questions · 25 min, without help. 5 topics of this module still to finish first.
- Then the next module, Arrays and strings. 60 topics left in the course before the final exam.
← Previous: Methods: parameters, return values and overloading