Exception Handling

☕ Java Lesson 15 Advanced

Exceptions are runtime disruptions that occur due to errors (e.g. file not found, index bounds, zero division). Proper handling prevents applications from crashing.

1 Checked vs. Unchecked Exceptions

Java divides exceptions into two primary branches:

  • Unchecked Exceptions (Runtime Exceptions): Occur due to programming logic mistakes (e.g. `NullPointerException`, `ArithmeticException`). The compiler does not force you to handle them.
  • Checked Exceptions: Checked at compilation time (e.g. `IOException`, `SQLException`). The compiler forces you to either handle them inside a `try-catch` block or declare them in your method signature using the `throws` keyword.
2 Try-Catch-Finally Flow Control

Let's look at standard error handling flow. The `finally` block is guaranteed to execute regardless of whether an exception is thrown or caught, which is useful for releasing system resources:

Java — Exceptions ▶ Run Code
public class Main {
    public static void main(String[] args) {
        try {
            int numerator = 10;
            int denominator = 0;
            int result = numerator / denominator; // 🚨 Throws ArithmeticException
            System.out.println("Result: " + result); // Will be skipped
        } catch (ArithmeticException e) {
            System.out.println("Exception caught: Cannot divide by zero!");
        } finally {
            System.out.println("Finally block executed! Resources closed.");
        }
        
        System.out.println("Program successfully continues running...");
    }
}
3 Code Challenge
Challenge: Write a method called `verifyAge(int age)` that throws an `IllegalArgumentException` if the age is negative. Call this method inside a try-catch block in `main()`, pass in a negative parameter value, catch the exception, and print its message.