Exception Handling
Lesson 15 of 20When code goes wrong, Java throws an object — trace try, catch and finally as the program refuses to crash.
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.
The life of an exception
From the broken line to recovery — follow one ArithmeticException on its journey.
Divide by zero, survive anyway
The throw happens on line 4 — watch the skip, the catch and the always-running finally.
1public class DivideDemo {2public static void main(String[] args) {3try {4int result = 10 / 0;5System.out.println(result);6} catch (ArithmeticException e) {7System.out.println("Cannot divide by zero");8} finally {9System.out.println("Done");10}11}12}
The JVM loads a tiny program with a try / catch / finally safety net.
try / catch / finally routes
Whether or not a throw happens, both roads meet at finally.
An out-of-bounds surprise
The array has 3 slots — line 5 asks for slot 5.
1public class TryDemo {2public static void main(String[] args) {3try {4int[] nums = {1, 2, 3};5System.out.println(nums[5]);6System.out.println("in try");7} catch (ArrayIndexOutOfBoundsException e) {8System.out.println("caught");9} finally {10System.out.println("finally");11}12}13}
Hint: The throw happens at nums[5] — everything after it inside try is skipped, and finally always runs.
Key takeaways
Exceptions are objects the JVM throws when something impossible happens.
The rest of the try block is abandoned the instant a throw occurs.
A catch block runs only if its exception type matches the thrown one.
finally runs on every path — exception or not — making it perfect for cleanup.
Checked exceptions (like IOException) must be caught or declared with throws.