Command Palette

Search for a command to run...

Back to the lesson: Topic 0.7 — Reading Compiler Errors and Stack Traces
Core Java · Example 1 of 3

Catching common runtime exceptions

Each try/catch catches the exception so the program keeps going (Topic 7.2). getClass().getSimpleName() is the exception type, getMessage() its message.

Java reports problems in two places: the compiler (javac) rejects code that breaks the rules, giving the file, line, a message and a caret ^ under the spot; and the JVM reports problems while running as an exception with a stack trace, a list of the method calls that led to the crash. Reading both calmly, top line first, is the most useful debugging skill you can learn.

Change the code and press Run (Ctrl+Enter). Try to predict the output first, then break it on purpose and read the error. Your edits are saved and match the lesson page.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write a program that catches the exception from Integer.parseInt("12a") and prints the exception's simple class name and message.

02

Write a program that safely prints the last element of {4, 8, 15} without hard-coding the index.

03

This method doesn't compile: static int sign(int n) { if (n > 0) return 1; else if (n < 0) return -1; }. Explain the error and fix it, then print sign(-5), sign(0) and sign(9).

Explain it without notes

01

What is the difference between a compile-time error, a runtime error and a logic error? Give an example of each.

02

Walk through every part of this message: Main.java:4: error: cannot find symbol with symbol: variable cuont and location: class Main.

03

How do you read a stack trace to find the bug quickly?

04

Why can fixing one compiler error make new errors appear?

05

What changed about NullPointerException messages in Java 14, and why does <local1> sometimes appear?

Catching common runtime exceptions
Sign in to run this example in your browser.

Expected output

ArithmeticException: / by zero
ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
NumberFormatException: For input string: "abc"
The program survived all three.