Appearance
Lesson 01 · Exceptions & the Hierarchy
Objectives
After this lesson you will be able to:
- Place
Throwable,Error,Exception, andRuntimeExceptionin the hierarchy. - Tell checked from unchecked exceptions and apply the handle-or-declare rule.
- Recognize common built-in exceptions and what triggers them.
The Throwable hierarchy
Only a Throwable can be thrown or caught. The tree splits into two branches:
Throwable
├── Error (unchecked — serious JVM problems; don't catch)
└── Exception (checked, EXCEPT...)
└── RuntimeException (unchecked — programming errors)Error(e.g.OutOfMemoryError,StackOverflowError) — abnormal conditions you normally can't recover from. Unchecked.RuntimeException(e.g.NullPointerException,IllegalArgumentException,ArrayIndexOutOfBoundsException) — bugs. Unchecked.- Other
Exceptions (e.g.IOException,SQLException) — recoverable conditions. Checked.
Checked vs unchecked
A checked exception must be handled or declared (the handle-or-declare rule): either catch it or list it in the method's throws clause, or the code won't compile. Unchecked exceptions (RuntimeException and Error and their subclasses) need neither.
java
void read() throws IOException { // checked — must declare or catch
Files.readString(Path.of("a.txt"));
}
int parse(String s) { // NumberFormatException is unchecked — no throws needed
return Integer.parseInt(s);
}Exam trap
NullPointerException, ArrayIndexOutOfBoundsException, ClassCastException, ArithmeticException, NumberFormatException, and IllegalArgumentException are all unchecked (RuntimeException subclasses). IOException and SQLException are checked. Know which is which — the exam tests whether a method needs a throws clause.
Throwing and the throws clause
throw raises an exception; throws (on the signature) declares what a method may propagate.
java
void check(int age) {
if (age < 0) throw new IllegalArgumentException("age < 0"); // unchecked
}Gotcha
An overriding method may not declare new or broader checked exceptions than the method it overrides — but it may declare fewer, narrower, or any unchecked ones. This pairs with the override rules from Module 03.
Key Takeaways
- Everything thrown is a
Throwable:ErrorandRuntimeExceptionare unchecked; otherExceptions are checked. - Checked exceptions follow handle-or-declare; unchecked ones don't.
- Common unchecked: NPE,
ArrayIndexOutOfBounds,ClassCast,Arithmetic,NumberFormat,IllegalArgument. Common checked:IOException,SQLException. - An override can't add broader checked exceptions, only narrower/fewer (or unchecked).
Lesson Quiz
Which exception is CHECKED?
Does Integer.parseInt require a throws clause on the caller?
Where does RuntimeException sit?
An overriding method may declare...
Should you normally catch an Error such as StackOverflowError?
Next: try / catch / finally. Run the matching code in labs/src/main/java/com/jse21/m04_exceptions/.