Skip to content

Beginner · Control flow and methods · topic 10 of 60 · 20 min

Reading errors and debugging

Explanation

Compile errors (cannot find symbol, incompatible types, missing return) are found by javac before running; read the file, line and caret. Run-time exceptions print a stack trace: the first line names the exception, and the first "at" line in YOUR code shows where it happened. An IDE debugger with breakpoints lets you pause and inspect variables.

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

MessageUsual causeFix
cannot find symbolA typo in a name, a missing import, or a variable used outside its scopeCheck spelling and case; add the import; declare the variable in the right block
incompatible types: X cannot be converted to YStoring a value of the wrong type (double into int, String into int)Change the type, cast, or parse
missing return statementA non-void method does not return on every pathAdd a final return or an else branch
';' expected / ')' expectedA missing semicolon or bracket, usually on the line BEFORE the caretLook at the end of the previous line
variable might not have been initializedA local variable read before a value is assignedGive it an initial value
unreachable statementCode after a return, break or infinite loopRemove or move the code

Reading a stack trace

output
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)
  1. Line 1: the exception type and message. Modern Java (14+) prints helpful NullPointerException messages that name the null variable.
  2. The "at" lines list the calls, newest first. Customer.java line 14 is where it crashed.
  3. Main.main called Report.print, which called Customer.initials. Go to the first line that is YOUR code (not java.* or a library).
  4. 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

  1. Click in the margin next to a line to set a breakpoint (a red dot).
  2. Start the program in Debug mode (the bug icon in IntelliJ IDEA, VS Code or Eclipse).
  3. When it pauses, look at the Variables panel; hover over any variable.
  4. Step Over (run this line), Step Into (go inside the method call), Step Out (finish this method), Resume (run to the next breakpoint).
  5. 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.

Careful: Do not "fix" an exception by wrapping everything in try/catch and ignoring it. The program then continues with wrong data. Find WHY the value was null or the index was wrong, and fix that.
Think of it like this: A stack trace is like the tracking history of a courier parcel, newest scan first. To find where it went wrong, you look for the first scan at YOUR warehouse, not the scans at other companies' hubs.
Tip: Search the exact error message (without your variable names) online; someone has almost always seen it before. Read the official explanation first, then Stack Overflow answers with care.

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

Errors and debugging

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.

java
String doctorName = (p.getDoctor() == null) ? "Not assigned" : p.getDoctor().getName();

Practice (0/3 done)

Task 1 · Question

javac reports "error: cannot find symbol symbol: variable totl". What is the most likely cause?

Task 2 · Question

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?

Task 3 · Practice

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

Question 1

1.Which error is found by the compiler, before running?

Question 2

2.In a stack trace, which "at" line is the place where the exception happened?

Question 3

3.Integer.parseInt("12a") throws…

Question 4

4.What does "Step Into" do in a debugger?

Read more (free)

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.

From Debugging like a pro: DevTools and VS Code

System.out.println("Sum: " + 2 + 3) prints…Related

Answer: Sum: 23

Left to right: "Sum: " + 2 is a String, then + 3 joins "3".

From Installing the JDK and your first program

What does a breakpoint do?Related

Answer: Pauses execution at a line so you can inspect values

Run in Debug mode to use it.

From Debugging and performance

Which flag adds debug information for gdb?Related

Answer: -g

Line numbers and variable names.

From Debugging with gdb

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: Arrays →

Next steps

  1. This is the last topic of “Control flow and methods”. The module exam comes next.
  2. Module 2 exam: Control flow and methods · 12 questions · 25 min, without help. 5 topics of this module still to finish first.
  3. Then the next module, Arrays and strings. 60 topics left in the course before the final exam.

← Previous: Methods: parameters, return values and overloading