Exception Handling

Lesson 15 of 20

When code goes wrong, Java throws an object — trace try, catch and finally as the program refuses to crash.

The big picture

Problems become objects

A crash in Java is not a mystery: the JVM throws an exception object that your catch block can grab and handle.

throw

When something impossible happens (10 / 0, a missing file), the JVM creates an exception and throws it.

try = danger zone

Code inside try is watched. The moment an exception appears, the rest of the block is skipped.

catch = safety net

catch (ArithmeticException e) runs only when that type is thrown — e carries the details.

finally = always

finally runs whether an exception happened or not — the right place for cleanup.