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.
Write a program that catches the exception from Integer.parseInt("12a") and prints the exception's simple class name and message.
Write a program that safely prints the last element of {4, 8, 15} without hard-coding the index.
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
What is the difference between a compile-time error, a runtime error and a logic error? Give an example of each.
Walk through every part of this message: Main.java:4: error: cannot find symbol with symbol: variable cuont and location: class Main.
How do you read a stack trace to find the bug quickly?
Why can fixing one compiler error make new errors appear?
What changed about NullPointerException messages in Java 14, and why does <local1> sometimes appear?
Expected output
ArithmeticException: / by zero
ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
NumberFormatException: For input string: "abc"
The program survived all three.