Your program reads a file that might not exist. Without exception handling, it crashes. With try-catch, you can detect the error and respond gracefully - show a message, try a different file, or use default data.

Basic try-catch

Catch and handle an exception.

denominator
BasicTryCatch.java
Replay: real traced execution (multi-file project)
// Basic Try-Catch: Division by Zero

public class BasicTryCatch {
    public static void main(String[] args) {
        System.out.println("=== Basic Try-Catch ===\n");

        // Without try-catch - would crash
        // int result = 10 / 0;  // ArithmeticException!

        // With try-catch - handle gracefully
        int numerator = 10;
        int denominator = 0;

        try {
            System.out.println("Attempting division...");
            int result = numerator / denominator;
            System.out.println("Result: " + result);
        } catch (ArithmeticException e) {
            System.out.println("Error caught!");
            System.out.println("Exception type: " + e.getClass().getName());
            System.out.println("Message: " + e.getMessage());
        }

        System.out.println("\nProgram continues normally...");

        // Demonstrate successful division
        System.out.println("\n--- Successful Division ---");

        int a = 20;
        int b = 4;

        try {
            int result = a / b;
            System.out.println(a + " / " + b + " = " + result);
        } catch (ArithmeticException e) {
            System.out.println("Error: " + e.getMessage());
        }

        // Multiple attempts in one try block
        System.out.println("\n--- Multiple Operations ---");

        int[] numbers = {10, 5, 0, 2};
        int dividend = 100;

        for (int num : numbers) {
            try {
                int result = dividend / num;
                System.out.println(dividend + " / " + num + " = " + result);
            } catch (ArithmeticException e) {
                System.out.println(dividend + " / " + num + " = Error (division by zero)");
            }
        }

        System.out.println("\n=== Key Points ===");
        System.out.println("""
            1. try block contains risky code
            2. catch block handles the exception
            3. Specify exception type to catch
            4. e.getMessage() gives error details
            5. Program continues after catch block
            """);
    }
}

//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
// Basic Try-Catch: Division by Zero

public class BasicTryCatch {
    public static void main(String[] args) {
        System.out.println("=== Basic Try-Catch ===\n");

        // Without try-catch - would crash
        // int result = 10 / 0;  // ArithmeticException!

        // With try-catch - handle gracefully
        int numerator = 10;
        int denominator = 2;

        try {
            System.out.println("Attempting division...");
            int result = numerator / denominator;
            System.out.println("Result: " + result);
        } catch (ArithmeticException e) {
            System.out.println("Error caught!");
            System.out.println("Exception type: " + e.getClass().getName());
            System.out.println("Message: " + e.getMessage());
        }

        System.out.println("\nProgram continues normally...");

        // Demonstrate successful division
        System.out.println("\n--- Successful Division ---");

        int a = 20;
        int b = 4;

        try {
            int result = a / b;
            System.out.println(a + " / " + b + " = " + result);
        } catch (ArithmeticException e) {
            System.out.println("Error: " + e.getMessage());
        }

        // Multiple attempts in one try block
        System.out.println("\n--- Multiple Operations ---");

        int[] numbers = {10, 5, 0, 2};
        int dividend = 100;

        for (int num : numbers) {
            try {
                int result = dividend / num;
                System.out.println(dividend + " / " + num + " = " + result);
            } catch (ArithmeticException e) {
                System.out.println(dividend + " / " + num + " = Error (division by zero)");
            }
        }

        System.out.println("\n=== Key Points ===");
        System.out.println("""
            1. try block contains risky code
            2. catch block handles the exception
            3. Specify exception type to catch
            4. e.getMessage() gives error details
            5. Program continues after catch block
            """);
    }
}

//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
  1. numerator ← 10, denominator ← 0

    3public class BasicTryCatch {4    public static void main(String[] args) {5        System.out.println("=== Basic Try-Catch ===\n");67        // Without try-catch - would crash //?without_try_catch8        // int result = 10 / 0;  // ArithmeticException!910        // With try-catch - handle gracefully //?with_try_catch11        int numerator→ 10 = 10; //?numerator12        int denominator→ 0 = 0; //?denominator13        //@denominator=0, 2
    output=== Basic Try-Catch ===
  2. try

    15try { //?try_block16    System.out.println("Attempting division..."); //?before_division17    int result = numerator10 / denominator0; //?division_attempt18    System.out.println("Result: " + result); //?after_division
    outputAttempting division...
  3. catch (ArithmeticException e)

    18    System.out.println("Result: " + result); //?after_division19} catch (ArithmeticException ejava.lang.ArithmeticException: / by zero) { //?catch_block20    System.out.println("Error caught!"); //?error_caught21    System.out.println("Exception type: " + e.getClass().getName()); //?exception_type22    System.out.println("Message: " + e.getMessage()); //?exception_message23}
    outputError caught!
    Exception type: java.lang.ArithmeticException
    Message: / by zero
  4. a ← 20, b ← 4

    25System.out.println("\nProgram continues normally..."); //?program_continues2627// Demonstrate successful division //?successful_demo28System.out.println("\n--- Successful Division ---");2930int a→ 20 = 20; //?var_a31int b→ 4 = 4; //?var_b
    output
    Program continues normally...
    
    --- Successful Division ---
  5. result ← 5

    33try { //?try_success34    int result→ 5 = a20 / b4; //?division_success35    System.out.println(a20 + " / " + b4 + " = " + result5); //?print_success36} catch (ArithmeticException e) { //?catch_success
    output20 / 4 = 5
  6. dividend ← 100

    40// Multiple attempts in one try block //?multiple_attempts41System.out.println("\n--- Multiple Operations ---");4243int[] numbers = {10, 5, 0, 2}; //?numbers_array44int dividend→ 100 = 100; //?dividend
    output
    --- Multiple Operations ---
  7. for (int num : numbers)

    pass 1 of 4
    46for (int num10 : numbers) { //?loop_numbers47    try { //?try_loop
    All 4 passes — pass 1 is the card above
    passnumedividend
    110
    25
    30java.lang.ArithmeticException: / by zero100
    42
  8. result ← 10

    pass 1 of 4
    46for (int num : numbers) { //?loop_numbers47    try { //?try_loop48        int result→ 10 = dividend100 / num10; //?division_loop49        System.out.println(dividend100 + " / " + num10 + " = " + result10); //?print_loop50    } catch (ArithmeticException e) { //?catch_loop
    output100 / 10 = 10
    All 4 passes — pass 1 is the card above
    passnumeresult
    11010
    2520
    30java.lang.ArithmeticException: / by zero
    4250
  9. catch (ArithmeticException e)

    49    System.out.println(dividend + " / " + num + " = " + result); //?print_loop50} catch (ArithmeticException ejava.lang.ArithmeticException: / by zero) { //?catch_loop51    System.out.println(dividend100 + " / " + num0 + " = Error (division by zero)"); //?error_loop52}
    output100 / 0 = Error (division by zero)
  10. System.out.println(" === Key Points ===");

    55    System.out.println("\n=== Key Points ===");56    System.out.println("""57        1. try block contains risky code58        2. catch block handles the exception59        3. Specify exception type to catch60        4. e.getMessage() gives error details61        5. Program continues after catch block62        """);63}
    output
    === Key Points ===
    1. try block contains risky code
    2. catch block handles the exception
    3. Specify exception type to catch
    4. e.getMessage() gives error details
    5. Program continues after catch block
  1. numerator ← 10, denominator ← 2

    3public class BasicTryCatch {4    public static void main(String[] args) {5        System.out.println("=== Basic Try-Catch ===\n");67        // Without try-catch - would crash8        // int result = 10 / 0;  // ArithmeticException!910        // With try-catch - handle gracefully11        int numerator→ 10 = 10;12        int denominator→ 2 = 2;
    output=== Basic Try-Catch ===
  2. result ← 5

    14try {15    System.out.println("Attempting division...");16    int result→ 5 = numerator10 / denominator2;17    System.out.println("Result: " + result5);18} catch (ArithmeticException e) {
    outputAttempting division...
    Result: 5
  3. a ← 20, b ← 4

    24System.out.println("\nProgram continues normally...");2526// Demonstrate successful division27System.out.println("\n--- Successful Division ---");2829int a→ 20 = 20;30int b→ 4 = 4;
    output
    Program continues normally...
    
    --- Successful Division ---
  4. result ← 5

    32try {33    int result→ 5 = a20 / b4;34    System.out.println(a20 + " / " + b4 + " = " + result5);35} catch (ArithmeticException e) {
    output20 / 4 = 5
  5. dividend ← 100

    39// Multiple attempts in one try block40System.out.println("\n--- Multiple Operations ---");4142int[] numbers = {10, 5, 0, 2};43int dividend→ 100 = 100;
    output
    --- Multiple Operations ---
  6. for (int num : numbers)

    pass 1 of 4
    45for (int num10 : numbers) {46    try {
    All 4 passes — pass 1 is the card above
    passnumedividend
    110
    25
    30java.lang.ArithmeticException: / by zero100
    42
  7. result ← 10

    pass 1 of 4
    45for (int num : numbers) {46    try {47        int result→ 10 = dividend100 / num10;48        System.out.println(dividend100 + " / " + num10 + " = " + result10);49    } catch (ArithmeticException e) {
    output100 / 10 = 10
    All 4 passes — pass 1 is the card above
    passnumeresult
    11010
    2520
    30java.lang.ArithmeticException: / by zero
    4250
  8. catch (ArithmeticException e)

    48    System.out.println(dividend + " / " + num + " = " + result);49} catch (ArithmeticException ejava.lang.ArithmeticException: / by zero) {50    System.out.println(dividend100 + " / " + num0 + " = Error (division by zero)");51}
    output100 / 0 = Error (division by zero)
  9. System.out.println(" === Key Points ===");

    54    System.out.println("\n=== Key Points ===");55    System.out.println("""56        1. try block contains risky code57        2. catch block handles the exception58        3. Specify exception type to catch59        4. e.getMessage() gives error details60        5. Program continues after catch block61        """);62}
    output
    === Key Points ===
    1. try block contains risky code
    2. catch block handles the exception
    3. Specify exception type to catch
    4. e.getMessage() gives error details
    5. Program continues after catch block

Code that might fail goes in try. Error handling goes in catch.

try-catch `try { risky code } catch (Exception e) { handle it }`. Prevents crashes.

Catch array bounds exception

Handle accessing invalid array indices.

requestedIndex
ArrayBounds.java
Replay: real traced execution (multi-file project)
// Array Index Out of Bounds Exception

public class ArrayBounds {
    public static void main(String[] args) {
        System.out.println("=== Array Bounds Exception ===\n");

        // Create an array
        String[] fruits = {"Apple", "Banana", "Cherry"};
        System.out.println("Array: [Apple, Banana, Cherry]");
        System.out.println("Valid indices: 0, 1, 2");
        System.out.println("Length: " + fruits.length);

        // Access valid index
        System.out.println("\n--- Valid Access ---");
        try {
            String fruit = fruits[1];
            System.out.println("fruits[1] = " + fruit);
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Error: " + e.getMessage());
        }

        // Access invalid index (too high)
        System.out.println("\n--- Invalid Access (index too high) ---");
        try {
            String fruit = fruits[5];
            System.out.println("fruits[5] = " + fruit);
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Error: Index 5 out of bounds");
            System.out.println("Message: " + e.getMessage());
        }

        // Access invalid index (negative)
        System.out.println("\n--- Invalid Access (negative index) ---");
        try {
            String fruit = fruits[-1];
            System.out.println("fruits[-1] = " + fruit);
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Error: Negative index");
            System.out.println("Message: " + e.getMessage());
        }

        // Safe access pattern
        System.out.println("\n--- Safe Access Pattern ---");
        int[] indicesToTry = {0, 2, 5, -1, 1};

        for (int index : indicesToTry) {
            try {
                String fruit = fruits[index];
                System.out.println("fruits[" + index + "] = " + fruit);
            } catch (ArrayIndexOutOfBoundsException e) {
                System.out.println("fruits[" + index + "] = Invalid index!");
            }
        }

        // Alternative: Check before accessing
        System.out.println("\n--- Check Before Access ---");
        int requestedIndex = 10;

        if (requestedIndex >= 0 && requestedIndex < fruits.length) {
            System.out.println("fruits[" + requestedIndex + "] = " + fruits[requestedIndex]);
        } else {
            System.out.println("Index " + requestedIndex + " is out of bounds (0-" + (fruits.length - 1) + ")");
        }

        System.out.println("\n=== Key Points ===");
        System.out.println("""
            1. Arrays have fixed size (0 to length-1)
            2. Invalid index throws ArrayIndexOutOfBoundsException
            3. Both too high AND negative indices are invalid
            4. Can catch and handle, or check bounds first
            5. getMessage() shows the invalid index number
            """);
    }
}

//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
// Array Index Out of Bounds Exception

public class ArrayBounds {
    public static void main(String[] args) {
        System.out.println("=== Array Bounds Exception ===\n");

        // Create an array
        String[] fruits = {"Apple", "Banana", "Cherry"};
        System.out.println("Array: [Apple, Banana, Cherry]");
        System.out.println("Valid indices: 0, 1, 2");
        System.out.println("Length: " + fruits.length);

        // Access valid index
        System.out.println("\n--- Valid Access ---");
        try {
            String fruit = fruits[1];
            System.out.println("fruits[1] = " + fruit);
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Error: " + e.getMessage());
        }

        // Access invalid index (too high)
        System.out.println("\n--- Invalid Access (index too high) ---");
        try {
            String fruit = fruits[5];
            System.out.println("fruits[5] = " + fruit);
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Error: Index 5 out of bounds");
            System.out.println("Message: " + e.getMessage());
        }

        // Access invalid index (negative)
        System.out.println("\n--- Invalid Access (negative index) ---");
        try {
            String fruit = fruits[-1];
            System.out.println("fruits[-1] = " + fruit);
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Error: Negative index");
            System.out.println("Message: " + e.getMessage());
        }

        // Safe access pattern
        System.out.println("\n--- Safe Access Pattern ---");
        int[] indicesToTry = {0, 2, 5, -1, 1};

        for (int index : indicesToTry) {
            try {
                String fruit = fruits[index];
                System.out.println("fruits[" + index + "] = " + fruit);
            } catch (ArrayIndexOutOfBoundsException e) {
                System.out.println("fruits[" + index + "] = Invalid index!");
            }
        }

        // Alternative: Check before accessing
        System.out.println("\n--- Check Before Access ---");
        int requestedIndex = -1;

        if (requestedIndex >= 0 && requestedIndex < fruits.length) {
            System.out.println("fruits[" + requestedIndex + "] = " + fruits[requestedIndex]);
        } else {
            System.out.println("Index " + requestedIndex + " is out of bounds (0-" + (fruits.length - 1) + ")");
        }

        System.out.println("\n=== Key Points ===");
        System.out.println("""
            1. Arrays have fixed size (0 to length-1)
            2. Invalid index throws ArrayIndexOutOfBoundsException
            3. Both too high AND negative indices are invalid
            4. Can catch and handle, or check bounds first
            5. getMessage() shows the invalid index number
            """);
    }
}

//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
// Array Index Out of Bounds Exception

public class ArrayBounds {
    public static void main(String[] args) {
        System.out.println("=== Array Bounds Exception ===\n");

        // Create an array
        String[] fruits = {"Apple", "Banana", "Cherry"};
        System.out.println("Array: [Apple, Banana, Cherry]");
        System.out.println("Valid indices: 0, 1, 2");
        System.out.println("Length: " + fruits.length);

        // Access valid index
        System.out.println("\n--- Valid Access ---");
        try {
            String fruit = fruits[1];
            System.out.println("fruits[1] = " + fruit);
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Error: " + e.getMessage());
        }

        // Access invalid index (too high)
        System.out.println("\n--- Invalid Access (index too high) ---");
        try {
            String fruit = fruits[5];
            System.out.println("fruits[5] = " + fruit);
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Error: Index 5 out of bounds");
            System.out.println("Message: " + e.getMessage());
        }

        // Access invalid index (negative)
        System.out.println("\n--- Invalid Access (negative index) ---");
        try {
            String fruit = fruits[-1];
            System.out.println("fruits[-1] = " + fruit);
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Error: Negative index");
            System.out.println("Message: " + e.getMessage());
        }

        // Safe access pattern
        System.out.println("\n--- Safe Access Pattern ---");
        int[] indicesToTry = {0, 2, 5, -1, 1};

        for (int index : indicesToTry) {
            try {
                String fruit = fruits[index];
                System.out.println("fruits[" + index + "] = " + fruit);
            } catch (ArrayIndexOutOfBoundsException e) {
                System.out.println("fruits[" + index + "] = Invalid index!");
            }
        }

        // Alternative: Check before accessing
        System.out.println("\n--- Check Before Access ---");
        int requestedIndex = 1;

        if (requestedIndex >= 0 && requestedIndex < fruits.length) {
            System.out.println("fruits[" + requestedIndex + "] = " + fruits[requestedIndex]);
        } else {
            System.out.println("Index " + requestedIndex + " is out of bounds (0-" + (fruits.length - 1) + ")");
        }

        System.out.println("\n=== Key Points ===");
        System.out.println("""
            1. Arrays have fixed size (0 to length-1)
            2. Invalid index throws ArrayIndexOutOfBoundsException
            3. Both too high AND negative indices are invalid
            4. Can catch and handle, or check bounds first
            5. getMessage() shows the invalid index number
            """);
    }
}

//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
  1. public static void main(String[] args)

    3public class ArrayBounds {4    public static void main(String[] args) {5        System.out.println("=== Array Bounds Exception ===\n");67        // Create an array //?create_array8        String[] fruits = {"Apple", "Banana", "Cherry"}; //?fruits_array9        System.out.println("Array: [Apple, Banana, Cherry]");10        System.out.println("Valid indices: 0, 1, 2");11        System.out.println("Length: " + fruits.length3);1213        // Access valid index //?valid_access14        System.out.println("\n--- Valid Access ---");15        try { //?try_valid
    output=== Array Bounds Exception ===
    Array: [Apple, Banana, Cherry]
    Valid indices: 0, 1, 2
    Length: 3
    
    --- Valid Access ---
  2. fruit ← Banana

    14System.out.println("\n--- Valid Access ---");15try { //?try_valid16    String fruit→ Banana = fruits[1]Banana; //?access_valid17    System.out.println("fruits[1] = " + fruitBanana); //?print_valid18} catch (ArrayIndexOutOfBoundsException e) { //?catch_valid
    outputfruits[1] = Banana
  3. System.out.println(" --- Invalid Access (index too high) ---");

    22// Access invalid index (too high) //?invalid_high23System.out.println("\n--- Invalid Access (index too high) ---");24try { //?try_high
    output
    --- Invalid Access (index too high) ---
  4. catch (ArrayIndexOutOfBoundsException e)

    26    System.out.println("fruits[5] = " + fruit); //?print_high27} catch (ArrayIndexOutOfBoundsException ejava.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 3) { //?catch_high28    System.out.println("Error: Index 5 out of bounds"); //?error_high29    System.out.println("Message: " + e.getMessage()); //?message_high30}
    outputError: Index 5 out of bounds
    Message: Index 5 out of bounds for length 3
  5. System.out.println(" --- Invalid Access (negative index) ---");

    32// Access invalid index (negative) //?invalid_negative33System.out.println("\n--- Invalid Access (negative index) ---");34try { //?try_negative
    output
    --- Invalid Access (negative index) ---
  6. catch (ArrayIndexOutOfBoundsException e)

    36    System.out.println("fruits[-1] = " + fruit); //?print_negative37} catch (ArrayIndexOutOfBoundsException ejava.lang.ArrayIndexOutOfBoundsException: Index -1 out of bounds for length 3) { //?catch_negative38    System.out.println("Error: Negative index"); //?error_negative39    System.out.println("Message: " + e.getMessage()); //?message_negative40}
    outputError: Negative index
    Message: Index -1 out of bounds for length 3
  7. int[] indicesToTry = {0, 2, 5, -1, 1}; //?indices_to_try

    42// Safe access pattern //?safe_pattern43System.out.println("\n--- Safe Access Pattern ---");44int[] indicesToTry = {0, 2, 5, -1, 1}; //?indices_to_try
    output
    --- Safe Access Pattern ---
  8. for (int index : indicesToTry)

    pass 1 of 5
    46for (int index0 : indicesToTry) { //?loop_indices47    try { //?try_safe
    All 5 passes — pass 1 is the card above
    passindexe
    10
    22
    35java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 3
    4-1java.lang.ArrayIndexOutOfBoundsException: Index -1 out of bounds for length 3
    51
  9. fruit ← Apple

    pass 1 of 5
    46for (int index : indicesToTry) { //?loop_indices47    try { //?try_safe48        String fruit→ Apple = fruits[index]Apple; //?access_safe49        System.out.println("fruits[" + index0 + "] = " + fruitApple); //?print_safe50    } catch (ArrayIndexOutOfBoundsException e) { //?catch_safe
    outputfruits[0] = Apple
    All 5 passes — pass 1 is the card above
    passfruits[index]indexefruit
    1Apple0Apple
    2Cherry2Cherry
    35java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 3
    4-1java.lang.ArrayIndexOutOfBoundsException: Index -1 out of bounds for length 3
    5Banana1Banana
  10. catch (ArrayIndexOutOfBoundsException e)

    pass 1 of 2
    49    System.out.println("fruits[" + index + "] = " + fruit); //?print_safe50} catch (ArrayIndexOutOfBoundsException ejava.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 3) { //?catch_safe51    System.out.println("fruits[" + index5 + "] = Invalid index!"); //?error_safe52}
    outputfruits[5] = Invalid index!
  11. catch (ArrayIndexOutOfBoundsException e)

    pass 2 of 2
    49    System.out.println("fruits[" + index + "] = " + fruit); //?print_safe50} catch (ArrayIndexOutOfBoundsException ejava.lang.ArrayIndexOutOfBoundsException: Index -1 out of bounds for length 3) { //?catch_safe51    System.out.println("fruits[" + index-1 + "] = Invalid index!"); //?error_safe52}
    outputfruits[-1] = Invalid index!
  12. requestedIndex ← 10

    55// Alternative: Check before accessing //?check_first56System.out.println("\n--- Check Before Access ---");57int requestedIndex→ 10 = 10; //?requested_index58//@requestedIndex=10, 1, -1
    output
    --- Check Before Access ---
  13. else

    61    System.out.println("fruits[" + requestedIndex + "] = " + fruits[requestedIndex]); //?safe_access62} else { //?else_invalid63    System.out.println("Index " + requestedIndex10 + " is out of bounds (0-" + (fruits.length3 - 1) + ")"); //?print_invalid64}
    outputIndex 10 is out of bounds (0-2)
  14. System.out.println(" === Key Points ===");

    66    System.out.println("\n=== Key Points ===");67    System.out.println("""68        1. Arrays have fixed size (0 to length-1)69        2. Invalid index throws ArrayIndexOutOfBoundsException70        3. Both too high AND negative indices are invalid71        4. Can catch and handle, or check bounds first72        5. getMessage() shows the invalid index number73        """);74}
    output
    === Key Points ===
    1. Arrays have fixed size (0 to length-1)
    2. Invalid index throws ArrayIndexOutOfBoundsException
    3. Both too high AND negative indices are invalid
    4. Can catch and handle, or check bounds first
    5. getMessage() shows the invalid index number
  1. public static void main(String[] args)

    3public class ArrayBounds {4    public static void main(String[] args) {5        System.out.println("=== Array Bounds Exception ===\n");67        // Create an array8        String[] fruits = {"Apple", "Banana", "Cherry"};9        System.out.println("Array: [Apple, Banana, Cherry]");10        System.out.println("Valid indices: 0, 1, 2");11        System.out.println("Length: " + fruits.length3);1213        // Access valid index14        System.out.println("\n--- Valid Access ---");15        try {
    output=== Array Bounds Exception ===
    Array: [Apple, Banana, Cherry]
    Valid indices: 0, 1, 2
    Length: 3
    
    --- Valid Access ---
  2. fruit ← Banana

    14System.out.println("\n--- Valid Access ---");15try {16    String fruit→ Banana = fruits[1]Banana;17    System.out.println("fruits[1] = " + fruitBanana);18} catch (ArrayIndexOutOfBoundsException e) {
    outputfruits[1] = Banana
  3. System.out.println(" --- Invalid Access (index too high) ---");

    22// Access invalid index (too high)23System.out.println("\n--- Invalid Access (index too high) ---");24try {
    output
    --- Invalid Access (index too high) ---
  4. catch (ArrayIndexOutOfBoundsException e)

    26    System.out.println("fruits[5] = " + fruit);27} catch (ArrayIndexOutOfBoundsException ejava.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 3) {28    System.out.println("Error: Index 5 out of bounds");29    System.out.println("Message: " + e.getMessage());30}
    outputError: Index 5 out of bounds
    Message: Index 5 out of bounds for length 3
  5. System.out.println(" --- Invalid Access (negative index) ---");

    32// Access invalid index (negative)33System.out.println("\n--- Invalid Access (negative index) ---");34try {
    output
    --- Invalid Access (negative index) ---
  6. catch (ArrayIndexOutOfBoundsException e)

    36    System.out.println("fruits[-1] = " + fruit);37} catch (ArrayIndexOutOfBoundsException ejava.lang.ArrayIndexOutOfBoundsException: Index -1 out of bounds for length 3) {38    System.out.println("Error: Negative index");39    System.out.println("Message: " + e.getMessage());40}
    outputError: Negative index
    Message: Index -1 out of bounds for length 3
  7. int[] indicesToTry = {0, 2, 5, -1, 1};

    42// Safe access pattern43System.out.println("\n--- Safe Access Pattern ---");44int[] indicesToTry = {0, 2, 5, -1, 1};
    output
    --- Safe Access Pattern ---
  8. for (int index : indicesToTry)

    pass 1 of 5
    46for (int index0 : indicesToTry) {47    try {
    All 5 passes — pass 1 is the card above
    passindexe
    10
    22
    35java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 3
    4-1java.lang.ArrayIndexOutOfBoundsException: Index -1 out of bounds for length 3
    51
  9. fruit ← Apple

    pass 1 of 5
    46for (int index : indicesToTry) {47    try {48        String fruit→ Apple = fruits[index]Apple;49        System.out.println("fruits[" + index0 + "] = " + fruitApple);50    } catch (ArrayIndexOutOfBoundsException e) {
    outputfruits[0] = Apple
    All 5 passes — pass 1 is the card above
    passfruits[index]indexefruit
    1Apple0Apple
    2Cherry2Cherry
    35java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 3
    4-1java.lang.ArrayIndexOutOfBoundsException: Index -1 out of bounds for length 3
    5Banana1Banana
  10. catch (ArrayIndexOutOfBoundsException e)

    pass 1 of 2
    49    System.out.println("fruits[" + index + "] = " + fruit);50} catch (ArrayIndexOutOfBoundsException ejava.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 3) {51    System.out.println("fruits[" + index5 + "] = Invalid index!");52}
    outputfruits[5] = Invalid index!
  11. catch (ArrayIndexOutOfBoundsException e)

    pass 2 of 2
    49    System.out.println("fruits[" + index + "] = " + fruit);50} catch (ArrayIndexOutOfBoundsException ejava.lang.ArrayIndexOutOfBoundsException: Index -1 out of bounds for length 3) {51    System.out.println("fruits[" + index-1 + "] = Invalid index!");52}
    outputfruits[-1] = Invalid index!
  12. requestedIndex ← -1

    55// Alternative: Check before accessing56System.out.println("\n--- Check Before Access ---");57int requestedIndex→ -1 = -1;
    output
    --- Check Before Access ---
  13. else

    60    System.out.println("fruits[" + requestedIndex + "] = " + fruits[requestedIndex]);61} else {62    System.out.println("Index " + requestedIndex-1 + " is out of bounds (0-" + (fruits.length3 - 1) + ")");63}
    outputIndex -1 is out of bounds (0-2)
  14. System.out.println(" === Key Points ===");

    65    System.out.println("\n=== Key Points ===");66    System.out.println("""67        1. Arrays have fixed size (0 to length-1)68        2. Invalid index throws ArrayIndexOutOfBoundsException69        3. Both too high AND negative indices are invalid70        4. Can catch and handle, or check bounds first71        5. getMessage() shows the invalid index number72        """);73}
    output
    === Key Points ===
    1. Arrays have fixed size (0 to length-1)
    2. Invalid index throws ArrayIndexOutOfBoundsException
    3. Both too high AND negative indices are invalid
    4. Can catch and handle, or check bounds first
    5. getMessage() shows the invalid index number
  1. public static void main(String[] args)

    3public class ArrayBounds {4    public static void main(String[] args) {5        System.out.println("=== Array Bounds Exception ===\n");67        // Create an array8        String[] fruits = {"Apple", "Banana", "Cherry"};9        System.out.println("Array: [Apple, Banana, Cherry]");10        System.out.println("Valid indices: 0, 1, 2");11        System.out.println("Length: " + fruits.length3);1213        // Access valid index14        System.out.println("\n--- Valid Access ---");15        try {
    output=== Array Bounds Exception ===
    Array: [Apple, Banana, Cherry]
    Valid indices: 0, 1, 2
    Length: 3
    
    --- Valid Access ---
  2. fruit ← Banana

    14System.out.println("\n--- Valid Access ---");15try {16    String fruit→ Banana = fruits[1]Banana;17    System.out.println("fruits[1] = " + fruitBanana);18} catch (ArrayIndexOutOfBoundsException e) {
    outputfruits[1] = Banana
  3. System.out.println(" --- Invalid Access (index too high) ---");

    22// Access invalid index (too high)23System.out.println("\n--- Invalid Access (index too high) ---");24try {
    output
    --- Invalid Access (index too high) ---
  4. catch (ArrayIndexOutOfBoundsException e)

    26    System.out.println("fruits[5] = " + fruit);27} catch (ArrayIndexOutOfBoundsException ejava.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 3) {28    System.out.println("Error: Index 5 out of bounds");29    System.out.println("Message: " + e.getMessage());30}
    outputError: Index 5 out of bounds
    Message: Index 5 out of bounds for length 3
  5. System.out.println(" --- Invalid Access (negative index) ---");

    32// Access invalid index (negative)33System.out.println("\n--- Invalid Access (negative index) ---");34try {
    output
    --- Invalid Access (negative index) ---
  6. catch (ArrayIndexOutOfBoundsException e)

    36    System.out.println("fruits[-1] = " + fruit);37} catch (ArrayIndexOutOfBoundsException ejava.lang.ArrayIndexOutOfBoundsException: Index -1 out of bounds for length 3) {38    System.out.println("Error: Negative index");39    System.out.println("Message: " + e.getMessage());40}
    outputError: Negative index
    Message: Index -1 out of bounds for length 3
  7. int[] indicesToTry = {0, 2, 5, -1, 1};

    42// Safe access pattern43System.out.println("\n--- Safe Access Pattern ---");44int[] indicesToTry = {0, 2, 5, -1, 1};
    output
    --- Safe Access Pattern ---
  8. for (int index : indicesToTry)

    pass 1 of 5
    46for (int index0 : indicesToTry) {47    try {
    All 5 passes — pass 1 is the card above
    passindexe
    10
    22
    35java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 3
    4-1java.lang.ArrayIndexOutOfBoundsException: Index -1 out of bounds for length 3
    51
  9. fruit ← Apple

    pass 1 of 5
    46for (int index : indicesToTry) {47    try {48        String fruit→ Apple = fruits[index]Apple;49        System.out.println("fruits[" + index0 + "] = " + fruitApple);50    } catch (ArrayIndexOutOfBoundsException e) {
    outputfruits[0] = Apple
    All 5 passes — pass 1 is the card above
    passfruits[index]indexefruit
    1Apple0Apple
    2Cherry2Cherry
    35java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 3
    4-1java.lang.ArrayIndexOutOfBoundsException: Index -1 out of bounds for length 3
    5Banana1Banana
  10. catch (ArrayIndexOutOfBoundsException e)

    pass 1 of 2
    49    System.out.println("fruits[" + index + "] = " + fruit);50} catch (ArrayIndexOutOfBoundsException ejava.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 3) {51    System.out.println("fruits[" + index5 + "] = Invalid index!");52}
    outputfruits[5] = Invalid index!
  11. catch (ArrayIndexOutOfBoundsException e)

    pass 2 of 2
    49    System.out.println("fruits[" + index + "] = " + fruit);50} catch (ArrayIndexOutOfBoundsException ejava.lang.ArrayIndexOutOfBoundsException: Index -1 out of bounds for length 3) {51    System.out.println("fruits[" + index-1 + "] = Invalid index!");52}
    outputfruits[-1] = Invalid index!
  12. requestedIndex ← 1

    55// Alternative: Check before accessing56System.out.println("\n--- Check Before Access ---");57int requestedIndex→ 1 = 1;
    output
    --- Check Before Access ---
  13. if (requestedIndex >= 0 && requestedIndex < fruits.length)

    59if (requestedIndex1 >= 0 && requestedIndex < fruits.length3) {60    System.out.println("fruits[" + requestedIndex1 + "] = " + fruits[requestedIndex]Banana);61} else {
    outputfruits[1] = Banana
  14. System.out.println(" === Key Points ===");

    65    System.out.println("\n=== Key Points ===");66    System.out.println("""67        1. Arrays have fixed size (0 to length-1)68        2. Invalid index throws ArrayIndexOutOfBoundsException69        3. Both too high AND negative indices are invalid70        4. Can catch and handle, or check bounds first71        5. getMessage() shows the invalid index number72        """);73}
    output
    === Key Points ===
    1. Arrays have fixed size (0 to length-1)
    2. Invalid index throws ArrayIndexOutOfBoundsException
    3. Both too high AND negative indices are invalid
    4. Can catch and handle, or check bounds first
    5. getMessage() shows the invalid index number

ArrayIndexOutOfBoundsException when accessing index outside array range.

Multiple catch blocks

Handle different exceptions differently.

MultipleCatch.java
Replay: real traced execution (multi-file project)
// Multiple Catch Blocks

public class MultipleCatch {
    public static void main(String[] args) {
        System.out.println("=== Multiple Catch Blocks ===\n");

        // Different exceptions need different handling
        String[] data = {"10", "abc", "20", null, "30"};
        int[] divisors = {2, 5, 0, 4, 1};

        System.out.println("Processing data with multiple exception types...\n");

        for (int i = 0; i < data.length; i++) {
            System.out.println("--- Processing index " + i + " ---");

            try {
                // Step 1: Parse string to int (may throw NumberFormatException)
                String str = data[i];
                System.out.println("String value: " + str);
                int number = Integer.parseInt(str);
                System.out.println("Parsed number: " + number);

                // Step 2: Divide (may throw ArithmeticException)
                int divisor = divisors[i];
                int result = number / divisor;
                System.out.println("Result: " + number + " / " + divisor + " = " + result);

            } catch (NumberFormatException e) {
                System.out.println("ERROR: Cannot parse '" + data[i] + "' as number");
                System.out.println("  Type: NumberFormatException");

            } catch (ArithmeticException e) {
                System.out.println("ERROR: Division by zero");
                System.out.println("  Type: ArithmeticException");

            } catch (NullPointerException e) {
                System.out.println("ERROR: Null value encountered");
                System.out.println("  Type: NullPointerException");
            }

            System.out.println();
        }

        // Multi-catch syntax (Java 7+)
        System.out.println("=== Multi-Catch Syntax ===\n");

        String[] testValues = {"100", "bad", null};
        int testDivisor = 10;

        for (String val : testValues) {
            try {
                int num = Integer.parseInt(val);
                int result = num / testDivisor;
                System.out.println(val + " / " + testDivisor + " = " + result);

            } catch (NumberFormatException | NullPointerException e) {
                // Handle both the same way
                System.out.println("Invalid input: " + val);
                System.out.println("  Exception: " + e.getClass().getSimpleName());
            }
        }

        // Order matters - specific before general
        System.out.println("\n=== Catch Order (Specific First) ===\n");

        demonstrateCatchOrder();

        System.out.println("=== Key Points ===");
        System.out.println("""
            1. Multiple catch blocks handle different exceptions
            2. Order: specific exceptions before general ones
            3. Multi-catch: catch (TypeA | TypeB e) for same handling
            4. Only ONE catch block executes per exception
            5. Put most specific exception types first
            """);
    }

    static void demonstrateCatchOrder() {
        String value = "not a number";

        try {
            int num = Integer.parseInt(value);
            System.out.println("Parsed: " + num);

        } catch (NumberFormatException e) {
            // Specific exception - caught first
            System.out.println("Caught NumberFormatException (specific)");

        } catch (IllegalArgumentException e) {
            // Parent of NumberFormatException - never reached for NFE
            System.out.println("Caught IllegalArgumentException (parent)");

        } catch (Exception e) {
            // Most general - catches anything else
            System.out.println("Caught Exception (general)");
        }

        System.out.println("\nNote: NumberFormatException extends IllegalArgumentException");
        System.out.println("So the specific catch must come first!");
    }
}

//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
  1. public static void main(String[] args)

    3public class MultipleCatch {4    public static void main(String[] args) {5        System.out.println("=== Multiple Catch Blocks ===\n");67        // Different exceptions need different handling //?different_exceptions8        String[] data = {"10", "abc", "20", null, "30"}; //?data_array9        int[] divisors = {2, 5, 0, 4, 1}; //?divisors_array1011        System.out.println("Processing data with multiple exception types...\n");
    output=== Multiple Catch Blocks ===
    Processing data with multiple exception types...
  2. for (int i = 0; i < data.length; i++)

    pass 1 of 5
    13for (int i0 = 0; i < data.length5; i++) { //?main_loop14    System.out.println("--- Processing index " + i0 + " ---");
    output--- Processing index 0 ---
    All 5 passes — pass 1 is the card above
    passiedata[i]
    10
    21java.lang.NumberFormatException: For input string: "abc"abc
    32java.lang.ArithmeticException: / by zero
    43java.lang.NumberFormatException: Cannot parse null stringnull
    54
  3. str ← 10, number ← 10, divisor ← 2, result ← 5

    pass 1 of 5
    16try { //?try_block17    // Step 1: Parse string to int (may throw NumberFormatException) //?step118    String str→ 10 = data[i]10; //?get_string19    System.out.println("String value: " + str10);20    int number→ 10 = Integer.parseInt(str10); //?parse_int21    System.out.println("Parsed number: " + number10);2223    // Step 2: Divide (may throw ArithmeticException) //?step224    int divisor→ 2 = divisors[i]2; //?get_divisor25    int result→ 5 = number10 / divisor2; //?divide26    System.out.println("Result: " + number10 + " / " + divisor2 + " = " + result5);
    outputString value: 10
    Parsed number: 10
    Result: 10 / 2 = 5
    All 5 passes — pass 1 is the card above
    passdata[i]idivisors[i]estrnumberdivisorresult
    11002101025
    2abc1java.lang.NumberFormatException: For input string: "abc"abc
    32020java.lang.ArithmeticException: / by zero20200
    4null3java.lang.NumberFormatException: Cannot parse null stringnull
    530413030130
  4. System.out.println();

    41    System.out.println();42}
  5. catch (NumberFormatException e)

    pass 1 of 2
    28} catch (NumberFormatException ejava.lang.NumberFormatException: For input string: "abc") { //?catch_number_format29    System.out.println("ERROR: Cannot parse '" + data[i]abc + "' as number");30    System.out.println("  Type: NumberFormatException");
    outputERROR: Cannot parse 'abc' as number
      Type: NumberFormatException
    values this step1i
  6. System.out.println();

    41    System.out.println();42}
  7. catch (ArithmeticException e)

    32} catch (ArithmeticException ejava.lang.ArithmeticException: / by zero) { //?catch_arithmetic33    System.out.println("ERROR: Division by zero");34    System.out.println("  Type: ArithmeticException");
    outputERROR: Division by zero
      Type: ArithmeticException
  8. System.out.println();

    41    System.out.println();42}
  9. catch (NumberFormatException e)

    pass 2 of 2
    28} catch (NumberFormatException ejava.lang.NumberFormatException: Cannot parse null string) { //?catch_number_format29    System.out.println("ERROR: Cannot parse '" + data[i]null + "' as number");30    System.out.println("  Type: NumberFormatException");
    outputERROR: Cannot parse 'null' as number
      Type: NumberFormatException
    values this step3i
  10. System.out.println();

    41    System.out.println();42}
  11. System.out.println();

    41    System.out.println();42}
  12. testDivisor ← 10

    44// Multi-catch syntax (Java 7+) //?multi_catch45System.out.println("=== Multi-Catch Syntax ===\n");4647String[] testValues = {"100", "bad", null}; //?test_values48int testDivisor→ 10 = 10; //?test_divisor
    output=== Multi-Catch Syntax ===
  13. for (String val : testValues)

    pass 1 of 3
    50for (String val100 : testValues) { //?multi_loop51    try { //?try_multi
    All 3 passes — pass 1 is the card above
    passvale
    1100
    2badjava.lang.NumberFormatException: For input string: "bad"
    3nulljava.lang.NumberFormatException: Cannot parse null string
  14. num ← 100, result ← 10

    pass 1 of 3
    50for (String val : testValues) { //?multi_loop51    try { //?try_multi52        int num→ 100 = Integer.parseInt(val100); //?parse_multi53        int result→ 10 = num100 / testDivisor10; //?divide_multi54        System.out.println(val100 + " / " + testDivisor10 + " = " + result10);
    output100 / 10 = 10
    All 3 passes — pass 1 is the card above
    passvaltestDivisorenumresult
    11001010010
    2badjava.lang.NumberFormatException: For input string: "bad"
    3nulljava.lang.NumberFormatException: Cannot parse null string
  15. catch (NumberFormatException | NullPointerException e)

    pass 1 of 2
    56} catch (NumberFormatException | NullPointerException ejava.lang.NumberFormatException: For input string: "bad") { //?multi_catch_block57    // Handle both the same way58    System.out.println("Invalid input: " + valbad);59    System.out.println("  Exception: " + e.getClass().getSimpleName());60}
    outputInvalid input: bad
      Exception: NumberFormatException
  16. catch (NumberFormatException | NullPointerException e)

    pass 2 of 2
    56} catch (NumberFormatException | NullPointerException ejava.lang.NumberFormatException: Cannot parse null string) { //?multi_catch_block57    // Handle both the same way58    System.out.println("Invalid input: " + valnull);59    System.out.println("  Exception: " + e.getClass().getSimpleName());60}
    outputInvalid input: null
      Exception: NumberFormatException
  17. System.out.println(" === Catch Order (Specific First) === ");

    63// Order matters - specific before general //?order_matters64System.out.println("\n=== Catch Order (Specific First) ===\n");6566demonstrateCatchOrder(); //?call_demo
    output
    === Catch Order (Specific First) ===
  18. value ← not a number

    78static void demonstrateCatchOrder() { //?demo_method79    String value→ not a number = "not a number"; //?demo_value
  19. try

    81try { //?try_order82    int num = Integer.parseInt(valuenot a number); //?parse_order83    System.out.println("Parsed: " + num);
  20. catch (NumberFormatException e)

    85} catch (NumberFormatException ejava.lang.NumberFormatException: For input string: "not a number") { //?catch_specific86    // Specific exception - caught first87    System.out.println("Caught NumberFormatException (specific)");
    outputCaught NumberFormatException (specific)
  21. System.out.println(" Note: NumberFormatException extends IllegalArgume…

    66    demonstrateCatchOrder(); //?call_demo6768    System.out.println("=== Key Points ===");69    System.out.println("""70        1. Multiple catch blocks handle different exceptions71        2. Order: specific exceptions before general ones72        3. Multi-catch: catch (TypeA | TypeB e) for same handling73        4. Only ONE catch block executes per exception74        5. Put most specific exception types first75        """);76}7778static void demonstrateCatchOrder() { //?demo_method79    String value = "not a number"; //?demo_value8081    try { //?try_order82        int num = Integer.parseInt(value); //?parse_order83        System.out.println("Parsed: " + num);8485    } catch (NumberFormatException e) { //?catch_specific86        // Specific exception - caught first87        System.out.println("Caught NumberFormatException (specific)");8889    } catch (IllegalArgumentException e) { //?catch_parent90        // Parent of NumberFormatException - never reached for NFE91        System.out.println("Caught IllegalArgumentException (parent)");9293    } catch (Exception e) { //?catch_general94        // Most general - catches anything else95        System.out.println("Caught Exception (general)");96    }9798    System.out.println("\nNote: NumberFormatException extends IllegalArgumentException");99    System.out.println("So the specific catch must come first!");100}
    output
    Note: NumberFormatException extends IllegalArgumentException
    So the specific catch must come first!
    === Key Points ===
    1. Multiple catch blocks handle different exceptions
    2. Order: specific exceptions before general ones
    3. Multi-catch: catch (TypeA | TypeB e) for same handling
    4. Only ONE catch block executes per exception
    5. Put most specific exception types first

Specific exceptions first, general exception last. Order matters.

multi-catch `catch (A | B e)` handles multiple types. Or use separate catch blocks.

Exception hierarchy

Catch parent type to handle all subtypes.

ExceptionHierarchy.java
Replay: real traced execution (multi-file project)
// Exception Hierarchy

public class ExceptionHierarchy {
    public static void main(String[] args) {
        System.out.println("=== Exception Hierarchy ===\n");

        // Exception inheritance tree
        System.out.println("Java Exception Hierarchy:");
        System.out.println("""
            Throwable
            ├── Error (serious, don't catch)
            │   ├── OutOfMemoryError
            │   └── StackOverflowError
            └── Exception (catch these)
                ├── RuntimeException (unchecked)
                │   ├── NullPointerException
                │   ├── ArithmeticException
                │   ├── IndexOutOfBoundsException
                │   │   └── ArrayIndexOutOfBoundsException
                │   ├── IllegalArgumentException
                │   │   └── NumberFormatException
                │   └── ClassCastException
                └── IOException (checked)
                    └── FileNotFoundException
            """);

        // Catching parent catches all children
        System.out.println("--- Parent Exception Catches Children ---\n");

        Object[] testCases = {
            "divide_zero",   // ArithmeticException
            "null_pointer",  // NullPointerException
            "bad_index",     // ArrayIndexOutOfBoundsException
            "bad_parse"      // NumberFormatException
        };

        for (Object testCase : testCases) {
            System.out.println("Test: " + testCase);

            try {
                triggerException((String)testCase);
            } catch (RuntimeException e) {
                // RuntimeException catches ALL runtime exceptions
                System.out.println("  Caught: " + e.getClass().getSimpleName());
                System.out.println("  Message: " + e.getMessage());
            }
            System.out.println();
        }

        // Catching Exception catches everything
        System.out.println("--- Catching Exception (Most General) ---\n");

        try {
            triggerException("null_pointer");
        } catch (Exception e) {
            System.out.println("Exception catches any exception type");
            System.out.println("Actual type: " + e.getClass().getName());
        }

        // instanceof check for specific handling
        System.out.println("\n--- instanceof for Specific Handling ---\n");

        for (Object testCase : testCases) {
            try {
                triggerException((String)testCase);
            } catch (Exception e) {
                handleWithInstanceof(e);
            }
        }

        // Why use specific exceptions?
        System.out.println("\n=== Why Catch Specific Exceptions? ===");
        System.out.println("""
            1. Different errors need different recovery
            2. Don't hide unexpected errors
            3. Better error messages for users
            4. Easier debugging
            5. Code is self-documenting
            """);
    }

    static void triggerException(String type) {
        switch (type) {
            case "divide_zero" -> {
                int result = 10 / 0;
            }
            case "null_pointer" -> {
                String s = null;
                s.length();
            }
            case "bad_index" -> {
                int[] arr = {1, 2, 3};
                int val = arr[10];
            }
            case "bad_parse" -> {
                int num = Integer.parseInt("abc");
            }
        }
    }

    static void handleWithInstanceof(Exception e) {
        System.out.print("Handling: ");

        if (e instanceof ArithmeticException) {
            System.out.println("Math error - check your calculations");
        } else if (e instanceof NullPointerException) {
            System.out.println("Null error - check for null values");
        } else if (e instanceof ArrayIndexOutOfBoundsException) {
            System.out.println("Index error - check array bounds");
        } else if (e instanceof NumberFormatException) {
            System.out.println("Parse error - check input format");
        } else {
            System.out.println("Unknown error: " + e.getClass().getSimpleName());
        }
    }
}

//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
  1. public static void main(String[] args)

    3public class ExceptionHierarchy {4    public static void main(String[] args) {5        System.out.println("=== Exception Hierarchy ===\n");67        // Exception inheritance tree //?inheritance_tree8        System.out.println("Java Exception Hierarchy:");9        System.out.println("""10            Throwable11            ├── Error (serious, don't catch)12            │   ├── OutOfMemoryError13            │   └── StackOverflowError14            └── Exception (catch these)15                ├── RuntimeException (unchecked)16                │   ├── NullPointerException17                │   ├── ArithmeticException18                │   ├── IndexOutOfBoundsException19                │   │   └── ArrayIndexOutOfBoundsException20                │   ├── IllegalArgumentException21                │   │   └── NumberFormatException22                │   └── ClassCastException23                └── IOException (checked)24                    └── FileNotFoundException25            """);2627        // Catching parent catches all children //?parent_catches_children28        System.out.println("--- Parent Exception Catches Children ---\n");2930        Object[] testCases = { //?test_cases31            "divide_zero",   // ArithmeticException32            "null_pointer",  // NullPointerException33            "bad_index",     // ArrayIndexOutOfBoundsException34            "bad_parse"      // NumberFormatException35        };
    output=== Exception Hierarchy ===
    Java Exception Hierarchy:
    Throwable
    ├── Error (serious, don't catch)
    │   ├── OutOfMemoryError
    │   └── StackOverflowError
    └── Exception (catch these)
        ├── RuntimeException (unchecked)
        │   ├── NullPointerException
        │   ├── ArithmeticException
        │   ├── IndexOutOfBoundsException
        │   │   └── ArrayIndexOutOfBoundsException
        │   ├── IllegalArgumentException
        │   │   └── NumberFormatException
        │   └── ClassCastException
        └── IOException (checked)
            └── FileNotFoundException
    --- Parent Exception Catches Children ---
  2. for (Object testCase : testCases)

    pass 1 of 4
    37for (Object testCasedivide_zero : testCases) { //?loop_tests38    System.out.println("Test: " + testCasedivide_zero);
    outputTest: divide_zero
    All 4 passes — pass 1 is the card above
    passtestCase
    1divide_zero
    2null_pointer
    3bad_index
    4bad_parse
  3. static void triggerException(String type)

    pass 1 of 9
    82static void triggerException(String typedivide_zero) { //?trigger_method83    switch (type) { //?switch_type
    All 9 passes — pass 1 is the card above
    passtypee
    1divide_zero
    2null_pointer
    3bad_index
    4bad_parse
    5null_pointerjava.lang.NullPointerException: Cannot invoke "String.length()" because "<local3>" is null
    6divide_zerojava.lang.ArithmeticException: / by zero
    7null_pointerjava.lang.NullPointerException: Cannot invoke "String.length()" because "<local3>" is null
    8bad_indexjava.lang.ArrayIndexOutOfBoundsException: Index 10 out of bounds for length 3
    9bad_parsejava.lang.NumberFormatException: For input string: "abc"
  4. catch (RuntimeException e)

    pass 1 of 4
    41    triggerException((String)testCase); //?trigger_exception42} catch (RuntimeException ejava.lang.ArithmeticException: / by zero) { //?catch_runtime43    // RuntimeException catches ALL runtime exceptions44    System.out.println("  Caught: " + e.getClass().getSimpleName());45    System.out.println("  Message: " + e.getMessage());46}
    output  Caught: ArithmeticException
      Message: / by zero
    All 4 passes — pass 1 is the card above
    passe
    1java.lang.ArithmeticException: / by zero
    2java.lang.NullPointerException: Cannot invoke "String.length()" because "<local3>" is null
    3java.lang.ArrayIndexOutOfBoundsException: Index 10 out of bounds for length 3
    4java.lang.NumberFormatException: For input string: "abc"
  5. System.out.println();

    46    }47    System.out.println();48}
  6. System.out.println();

    46    }47    System.out.println();48}
  7. System.out.println();

    46    }47    System.out.println();48}
  8. System.out.println();

    46    }47    System.out.println();48}4950// Catching Exception catches everything //?catch_all51System.out.println("--- Catching Exception (Most General) ---\n");
    output--- Catching Exception (Most General) ---
  9. catch (Exception e)

    54    triggerException("null_pointer"); //?trigger_null55} catch (Exception ejava.lang.NullPointerException: Cannot invoke "String.length()" because "<local3>" is null) { //?catch_exception56    System.out.println("Exception catches any exception type");57    System.out.println("Actual type: " + e.getClass().getName());58}
    outputException catches any exception type
    Actual type: java.lang.NullPointerException
  10. System.out.println(" --- instanceof for Specific Handling --- ");

    60// instanceof check for specific handling //?instanceof_check61System.out.println("\n--- instanceof for Specific Handling ---\n");
    output
    --- instanceof for Specific Handling ---
  11. for (Object testCase : testCases)

    pass 1 of 4
    63for (Object testCasedivide_zero : testCases) { //?loop_instanceof64    try { //?try_instanceof
    All 4 passes — pass 1 is the card above
    passtestCasee
    1divide_zerojava.lang.ArithmeticException: / by zero
    2null_pointerjava.lang.NullPointerException: Cannot invoke "String.length()" because "<local3>" is null
    3bad_indexjava.lang.ArrayIndexOutOfBoundsException: Index 10 out of bounds for length 3
    4bad_parsejava.lang.NumberFormatException: For input string: "abc"
  12. try

    pass 1 of 4
    63for (Object testCase : testCases) { //?loop_instanceof64    try { //?try_instanceof65        triggerException((String)testCase); //?trigger_instanceof66    } catch (Exception e) { //?catch_instanceof
    All 4 passes — pass 1 is the card above
    passe
    1java.lang.ArithmeticException: / by zero
    2java.lang.NullPointerException: Cannot invoke "String.length()" because "<local3>" is null
    3java.lang.ArrayIndexOutOfBoundsException: Index 10 out of bounds for length 3
    4java.lang.NumberFormatException: For input string: "abc"
  13. catch (Exception e)

    pass 1 of 4
    65    triggerException((String)testCase); //?trigger_instanceof66} catch (Exception ejava.lang.ArithmeticException: / by zero) { //?catch_instanceof67    handleWithInstanceof(ejava.lang.ArithmeticException: / by zero); //?handle_instanceof68}
    All 4 passes — pass 1 is the card above
    passe
    1java.lang.ArithmeticException: / by zero
    2java.lang.NullPointerException: Cannot invoke "String.length()" because "<local3>" is null
    3java.lang.ArrayIndexOutOfBoundsException: Index 10 out of bounds for length 3
    4java.lang.NumberFormatException: For input string: "abc"
  14. static void handleWithInstanceof(Exception e)

    pass 1 of 4
    101static void handleWithInstanceof(Exception ejava.lang.ArithmeticException: / by zero) { //?handle_method102    System.out.print("Handling: ");
    outputHandling: 
    All 4 passes — pass 1 is the card above
    passe
    1java.lang.ArithmeticException: / by zero
    2java.lang.NullPointerException: Cannot invoke "String.length()" because "<local3>" is null
    3java.lang.ArrayIndexOutOfBoundsException: Index 10 out of bounds for length 3
    4java.lang.NumberFormatException: For input string: "abc"
  15. if (e instanceof ArithmeticException)

    66        } catch (Exception e) { //?catch_instanceof67            handleWithInstanceof(ejava.lang.ArithmeticException: / by zero); //?handle_instanceof68        }69    }7071    // Why use specific exceptions? //?why_specific72    System.out.println("\n=== Why Catch Specific Exceptions? ===");73    System.out.println("""74        1. Different errors need different recovery75        2. Don't hide unexpected errors76        3. Better error messages for users77        4. Easier debugging78        5. Code is self-documenting79        """);80}8182static void triggerException(String type) { //?trigger_method83    switch (type) { //?switch_type84        case "divide_zero" -> { //?case_divide85            int result = 10 / 0;86        }87        case "null_pointer" -> { //?case_null88            String s = null;89            s.length();90        }91        case "bad_index" -> { //?case_index92            int[] arr = {1, 2, 3};93            int val = arr[10];94        }95        case "bad_parse" -> { //?case_parse96            int num = Integer.parseInt("abc");97        }98    }99}100101static void handleWithInstanceof(Exception e) { //?handle_method102    System.out.print("Handling: ");103104    if (e instanceof ArithmeticException) { //?check_arithmetic105        System.out.println("Math error - check your calculations");106    } else if (e instanceof NullPointerException) { //?check_null
    outputMath error - check your calculations
  16. if (e instanceof NullPointerException)

    66        } catch (Exception e) { //?catch_instanceof67            handleWithInstanceof(ejava.lang.NullPointerException: Cannot invoke "String.length()" because "<local3>" is null); //?handle_instanceof68        }69    }7071    // Why use specific exceptions? //?why_specific72    System.out.println("\n=== Why Catch Specific Exceptions? ===");73    System.out.println("""74        1. Different errors need different recovery75        2. Don't hide unexpected errors76        3. Better error messages for users77        4. Easier debugging78        5. Code is self-documenting79        """);80}8182static void triggerException(String type) { //?trigger_method83    switch (type) { //?switch_type84        case "divide_zero" -> { //?case_divide85            int result = 10 / 0;86        }87        case "null_pointer" -> { //?case_null88            String s = null;89            s.length();90        }91        case "bad_index" -> { //?case_index92            int[] arr = {1, 2, 3};93            int val = arr[10];94        }95        case "bad_parse" -> { //?case_parse96            int num = Integer.parseInt("abc");97        }98    }99}100101static void handleWithInstanceof(Exception e) { //?handle_method102    System.out.print("Handling: ");103104    if (e instanceof ArithmeticException) { //?check_arithmetic105        System.out.println("Math error - check your calculations");106    } else if (e instanceof NullPointerException) { //?check_null107        System.out.println("Null error - check for null values");108    } else if (e instanceof ArrayIndexOutOfBoundsException) { //?check_array
    outputNull error - check for null values
  17. if (e instanceof ArrayIndexOutOfBoundsException)

    66        } catch (Exception e) { //?catch_instanceof67            handleWithInstanceof(ejava.lang.ArrayIndexOutOfBoundsException: Index 10 out of bounds for length 3); //?handle_instanceof68        }69    }7071    // Why use specific exceptions? //?why_specific72    System.out.println("\n=== Why Catch Specific Exceptions? ===");73    System.out.println("""74        1. Different errors need different recovery75        2. Don't hide unexpected errors76        3. Better error messages for users77        4. Easier debugging78        5. Code is self-documenting79        """);80}8182static void triggerException(String type) { //?trigger_method83    switch (type) { //?switch_type84        case "divide_zero" -> { //?case_divide85            int result = 10 / 0;86        }87        case "null_pointer" -> { //?case_null88            String s = null;89            s.length();90        }91        case "bad_index" -> { //?case_index92            int[] arr = {1, 2, 3};93            int val = arr[10];94        }95        case "bad_parse" -> { //?case_parse96            int num = Integer.parseInt("abc");97        }98    }99}100101static void handleWithInstanceof(Exception e) { //?handle_method102    System.out.print("Handling: ");103104    if (e instanceof ArithmeticException) { //?check_arithmetic105        System.out.println("Math error - check your calculations");106    } else if (e instanceof NullPointerException) { //?check_null107        System.out.println("Null error - check for null values");108    } else if (e instanceof ArrayIndexOutOfBoundsException) { //?check_array109        System.out.println("Index error - check array bounds");110    } else if (e instanceof NumberFormatException) { //?check_number
    outputIndex error - check array bounds
  18. if (e instanceof NumberFormatException)

    66        } catch (Exception e) { //?catch_instanceof67            handleWithInstanceof(ejava.lang.NumberFormatException: For input string: "abc"); //?handle_instanceof68        }69    }7071    // Why use specific exceptions? //?why_specific72    System.out.println("\n=== Why Catch Specific Exceptions? ===");73    System.out.println("""74        1. Different errors need different recovery75        2. Don't hide unexpected errors76        3. Better error messages for users77        4. Easier debugging78        5. Code is self-documenting79        """);80}8182static void triggerException(String type) { //?trigger_method83    switch (type) { //?switch_type84        case "divide_zero" -> { //?case_divide85            int result = 10 / 0;86        }87        case "null_pointer" -> { //?case_null88            String s = null;89            s.length();90        }91        case "bad_index" -> { //?case_index92            int[] arr = {1, 2, 3};93            int val = arr[10];94        }95        case "bad_parse" -> { //?case_parse96            int num = Integer.parseInt("abc");97        }98    }99}100101static void handleWithInstanceof(Exception e) { //?handle_method102    System.out.print("Handling: ");103104    if (e instanceof ArithmeticException) { //?check_arithmetic105        System.out.println("Math error - check your calculations");106    } else if (e instanceof NullPointerException) { //?check_null107        System.out.println("Null error - check for null values");108    } else if (e instanceof ArrayIndexOutOfBoundsException) { //?check_array109        System.out.println("Index error - check array bounds");110    } else if (e instanceof NumberFormatException) { //?check_number111        System.out.println("Parse error - check input format");112    } else { //?check_other
    outputParse error - check input format
    
    === Why Catch Specific Exceptions? ===
    1. Different errors need different recovery
    2. Don't hide unexpected errors
    3. Better error messages for users
    4. Easier debugging
    5. Code is self-documenting

Catching Exception catches everything. Be specific when possible.

Finally block

Code that always runs, even after exception.

FinallyBlock.java
Replay: real traced execution (multi-file project)
// Finally Block

public class FinallyBlock {
    public static void main(String[] args) {
        System.out.println("=== Finally Block ===\n");

        // Finally always executes
        System.out.println("--- Finally with Exception ---");

        try {
            System.out.println("1. In try block");
            int result = 10 / 0;
            System.out.println("2. This won't print");
        } catch (ArithmeticException e) {
            System.out.println("3. In catch block");
        } finally {
            System.out.println("4. In finally block (ALWAYS runs)");
        }

        System.out.println("5. After try-catch-finally");

        // Finally without exception
        System.out.println("\n--- Finally without Exception ---");

        try {
            System.out.println("1. In try block");
            int result = 10 / 2;
            System.out.println("2. Result: " + result);
        } catch (ArithmeticException e) {
            System.out.println("3. In catch block (SKIPPED)");
        } finally {
            System.out.println("4. In finally block (ALWAYS runs)");
        }

        System.out.println("5. After try-catch-finally");

        // Finally for cleanup
        System.out.println("\n--- Finally for Cleanup ---");

        demonstrateCleanup(true);
        System.out.println();
        demonstrateCleanup(false);

        // Finally with return
        System.out.println("\n--- Finally with Return ---");

        int result1 = calculateWithReturn(10, 2);
        System.out.println("Result: " + result1);

        int result2 = calculateWithReturn(10, 0);
        System.out.println("Result: " + result2);

        // Try-finally without catch
        System.out.println("\n--- Try-Finally (no catch) ---");

        try {
            System.out.println("Performing operation...");
            // Operations here
        } finally {
            System.out.println("Cleanup runs even without catch block");
        }

        System.out.println("\n=== Key Points ===");
        System.out.println("""
            1. finally ALWAYS executes
            2. Executes after try OR after catch
            3. Use for cleanup: close files, release resources
            4. finally runs even if return in try/catch
            5. Can have try-finally without catch
            """);
    }

    static void demonstrateCleanup(boolean success) {
        System.out.println("Starting operation (success=" + success + ")");

        // Simulating resource acquisition
        System.out.println("  [RESOURCE] Acquired");

        try {
            if (success) {
                System.out.println("  [OPERATION] Success");
            } else {
                System.out.println("  [OPERATION] About to fail...");
                throw new RuntimeException("Operation failed");
            }
        } catch (RuntimeException e) {
            System.out.println("  [ERROR] " + e.getMessage());
        } finally {
            // Always release the resource
            System.out.println("  [RESOURCE] Released (finally)");
        }
    }

    static int calculateWithReturn(int a, int b) {
        try {
            int result = a / b;
            System.out.println("  Calculation successful");
            return result;
        } catch (ArithmeticException e) {
            System.out.println("  Calculation failed");
            return -1;
        } finally {
            // This runs BEFORE the return!
            System.out.println("  Finally block executed");
        }
    }
}

//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
  1. public static void main(String[] args)

    3public class FinallyBlock {4    public static void main(String[] args) {5        System.out.println("=== Finally Block ===\n");67        // Finally always executes //?finally_always8        System.out.println("--- Finally with Exception ---");
    output=== Finally Block ===
    --- Finally with Exception ---
  2. try

    10try { //?try_exception11    System.out.println("1. In try block");12    int result = 10 / 0; //?cause_exception13    System.out.println("2. This won't print");
    output1. In try block
  3. catch (ArithmeticException e)

    13    System.out.println("2. This won't print");14} catch (ArithmeticException ejava.lang.ArithmeticException: / by zero) { //?catch_exception15    System.out.println("3. In catch block");16} finally { //?finally_exception
    output3. In catch block
  4. 15    System.out.println("3. In catch block");16} finally { //?finally_exception17    System.out.println("4. In finally block (ALWAYS runs)");18}
    output4. In finally block (ALWAYS runs)
  5. System.out.println("5. After try-catch-finally");

    20System.out.println("5. After try-catch-finally");2122// Finally without exception //?finally_no_exception23System.out.println("\n--- Finally without Exception ---");
    output5. After try-catch-finally
    
    --- Finally without Exception ---
  6. result ← 5

    25try { //?try_no_exception26    System.out.println("1. In try block");27    int result→ 5 = 10 / 2; //?no_exception28    System.out.println("2. Result: " + result5);29} catch (ArithmeticException e) { //?catch_no_exception
    output1. In try block
    2. Result: 5
  7. 30    System.out.println("3. In catch block (SKIPPED)");31} finally { //?finally_no_exception_block32    System.out.println("4. In finally block (ALWAYS runs)");33}
    output4. In finally block (ALWAYS runs)
  8. System.out.println("5. After try-catch-finally");

    35System.out.println("5. After try-catch-finally");3637// Finally for cleanup //?finally_cleanup38System.out.println("\n--- Finally for Cleanup ---");3940demonstrateCleanup(true); //?demo_success41System.out.println();
    output5. After try-catch-finally
    
    --- Finally for Cleanup ---
  9. static void demonstrateCleanup(boolean success)

    pass 1 of 2
    73static void demonstrateCleanup(boolean successtrue) { //?cleanup_method74    System.out.println("Starting operation (success=" + successtrue + ")");7576    // Simulating resource acquisition //?simulate_resource77    System.out.println("  [RESOURCE] Acquired");
    outputStarting operation (success=true)
      [RESOURCE] Acquired
  10. if (success)

    79try { //?try_cleanup80    if (successtrue) { //?check_success81        System.out.println("  [OPERATION] Success");82    } else { //?operation_fail
    output  [OPERATION] Success
  11. pass 1 of 2
    40    demonstrateCleanup(true); //?demo_success41    System.out.println();42    demonstrateCleanup(false); //?demo_failure4344    // Finally with return //?finally_return45    System.out.println("\n--- Finally with Return ---");4647    int result1 = calculateWithReturn(10, 2); //?call_return_success48    System.out.println("Result: " + result1);4950    int result2 = calculateWithReturn(10, 0); //?call_return_error51    System.out.println("Result: " + result2);5253    // Try-finally without catch //?try_finally_only54    System.out.println("\n--- Try-Finally (no catch) ---");5556    try { //?try_only57        System.out.println("Performing operation...");58        // Operations here59    } finally { //?finally_only60        System.out.println("Cleanup runs even without catch block");61    }6263    System.out.println("\n=== Key Points ===");64    System.out.println("""65        1. finally ALWAYS executes66        2. Executes after try OR after catch67        3. Use for cleanup: close files, release resources68        4. finally runs even if return in try/catch69        5. Can have try-finally without catch70        """);71}7273static void demonstrateCleanup(boolean success) { //?cleanup_method74    System.out.println("Starting operation (success=" + success + ")");7576    // Simulating resource acquisition //?simulate_resource77    System.out.println("  [RESOURCE] Acquired");7879    try { //?try_cleanup80        if (success) { //?check_success81            System.out.println("  [OPERATION] Success");82        } else { //?operation_fail83            System.out.println("  [OPERATION] About to fail...");84            throw new RuntimeException("Operation failed"); //?throw_exception85        }86    } catch (RuntimeException e) { //?catch_cleanup87        System.out.println("  [ERROR] " + e.getMessage());88    } finally { //?finally_cleanup_block89        // Always release the resource90        System.out.println("  [RESOURCE] Released (finally)"); //?release_resource91    }
    output  [RESOURCE] Released (finally)
  12. static void demonstrateCleanup(boolean success)

    pass 2 of 2
    73static void demonstrateCleanup(boolean successfalse) { //?cleanup_method74    System.out.println("Starting operation (success=" + successfalse + ")");7576    // Simulating resource acquisition //?simulate_resource77    System.out.println("  [RESOURCE] Acquired");
    outputStarting operation (success=false)
      [RESOURCE] Acquired
  13. else

    81    System.out.println("  [OPERATION] Success");82} else { //?operation_fail83    System.out.println("  [OPERATION] About to fail...");84    throw new RuntimeException("Operation failed"); //?throw_exception85}
    output  [OPERATION] About to fail...
  14. catch (RuntimeException e)

    85    }86} catch (RuntimeException ejava.lang.RuntimeException: Operation failed) { //?catch_cleanup87    System.out.println("  [ERROR] " + e.getMessage());88} finally { //?finally_cleanup_block
    output  [ERROR] Operation failed
  15. pass 2 of 2
    41    System.out.println();42    demonstrateCleanup(false); //?demo_failure4344    // Finally with return //?finally_return45    System.out.println("\n--- Finally with Return ---");4647    int result1 = calculateWithReturn(10, 2); //?call_return_success48    System.out.println("Result: " + result1);4950    int result2 = calculateWithReturn(10, 0); //?call_return_error51    System.out.println("Result: " + result2);5253    // Try-finally without catch //?try_finally_only54    System.out.println("\n--- Try-Finally (no catch) ---");5556    try { //?try_only57        System.out.println("Performing operation...");58        // Operations here59    } finally { //?finally_only60        System.out.println("Cleanup runs even without catch block");61    }6263    System.out.println("\n=== Key Points ===");64    System.out.println("""65        1. finally ALWAYS executes66        2. Executes after try OR after catch67        3. Use for cleanup: close files, release resources68        4. finally runs even if return in try/catch69        5. Can have try-finally without catch70        """);71}7273static void demonstrateCleanup(boolean success) { //?cleanup_method74    System.out.println("Starting operation (success=" + success + ")");7576    // Simulating resource acquisition //?simulate_resource77    System.out.println("  [RESOURCE] Acquired");7879    try { //?try_cleanup80        if (success) { //?check_success81            System.out.println("  [OPERATION] Success");82        } else { //?operation_fail83            System.out.println("  [OPERATION] About to fail...");84            throw new RuntimeException("Operation failed"); //?throw_exception85        }86    } catch (RuntimeException e) { //?catch_cleanup87        System.out.println("  [ERROR] " + e.getMessage());88    } finally { //?finally_cleanup_block89        // Always release the resource90        System.out.println("  [RESOURCE] Released (finally)"); //?release_resource91    }
    output  [RESOURCE] Released (finally)
    
    --- Finally with Return ---
  16. static int calculateWithReturn(int a, int b)

    pass 1 of 2
    94static int calculateWithReturn(int a10, int b2) { //?return_method95    try { //?try_return
  17. result ← 5

    pass 1 of 2
    94static int calculateWithReturn(int a, int b) { //?return_method95    try { //?try_return96        int result→ 5 = a10 / b2; //?calc_return97        System.out.println("  Calculation successful");98        return result5; //?return_success99    } catch (ArithmeticException e) { //?catch_return
    output  Calculation successful
  18. result1 ← 5

    pass 1 of 2
    47    int result1→ 5 = calculateWithReturn(10, 2); //?call_return_success48    System.out.println("Result: " + result15);4950    int result2 = calculateWithReturn(10, 0); //?call_return_error51    System.out.println("Result: " + result2);5253    // Try-finally without catch //?try_finally_only54    System.out.println("\n--- Try-Finally (no catch) ---");5556    try { //?try_only57        System.out.println("Performing operation...");58        // Operations here59    } finally { //?finally_only60        System.out.println("Cleanup runs even without catch block");61    }6263    System.out.println("\n=== Key Points ===");64    System.out.println("""65        1. finally ALWAYS executes66        2. Executes after try OR after catch67        3. Use for cleanup: close files, release resources68        4. finally runs even if return in try/catch69        5. Can have try-finally without catch70        """);71}7273static void demonstrateCleanup(boolean success) { //?cleanup_method74    System.out.println("Starting operation (success=" + success + ")");7576    // Simulating resource acquisition //?simulate_resource77    System.out.println("  [RESOURCE] Acquired");7879    try { //?try_cleanup80        if (success) { //?check_success81            System.out.println("  [OPERATION] Success");82        } else { //?operation_fail83            System.out.println("  [OPERATION] About to fail...");84            throw new RuntimeException("Operation failed"); //?throw_exception85        }86    } catch (RuntimeException e) { //?catch_cleanup87        System.out.println("  [ERROR] " + e.getMessage());88    } finally { //?finally_cleanup_block89        // Always release the resource90        System.out.println("  [RESOURCE] Released (finally)"); //?release_resource91    }92}9394static int calculateWithReturn(int a, int b) { //?return_method95    try { //?try_return96        int result = a / b; //?calc_return97        System.out.println("  Calculation successful");98        return result; //?return_success99    } catch (ArithmeticException e) { //?catch_return100        System.out.println("  Calculation failed");101        return -1; //?return_error102    } finally { //?finally_return_block103        // This runs BEFORE the return!104        System.out.println("  Finally block executed"); //?finally_before_return105    }
    output  Finally block executed
    Result: 5
  19. static int calculateWithReturn(int a, int b)

    pass 2 of 2
    94static int calculateWithReturn(int a10, int b0) { //?return_method95    try { //?try_return
  20. try

    pass 2 of 2
    94static int calculateWithReturn(int a, int b) { //?return_method95    try { //?try_return96        int result = a10 / b0; //?calc_return97        System.out.println("  Calculation successful");
  21. catch (ArithmeticException e)

    98    return result; //?return_success99} catch (ArithmeticException ejava.lang.ArithmeticException: / by zero) { //?catch_return100    System.out.println("  Calculation failed");101    return -1; //?return_error102} finally { //?finally_return_block
    output  Calculation failed
  22. result2 ← -1

    pass 2 of 2
    50    int result2→ -1 = calculateWithReturn(10, 0); //?call_return_error51    System.out.println("Result: " + result2-1);5253    // Try-finally without catch //?try_finally_only54    System.out.println("\n--- Try-Finally (no catch) ---");5556    try { //?try_only57        System.out.println("Performing operation...");58        // Operations here59    } finally { //?finally_only60        System.out.println("Cleanup runs even without catch block");61    }6263    System.out.println("\n=== Key Points ===");64    System.out.println("""65        1. finally ALWAYS executes66        2. Executes after try OR after catch67        3. Use for cleanup: close files, release resources68        4. finally runs even if return in try/catch69        5. Can have try-finally without catch70        """);71}7273static void demonstrateCleanup(boolean success) { //?cleanup_method74    System.out.println("Starting operation (success=" + success + ")");7576    // Simulating resource acquisition //?simulate_resource77    System.out.println("  [RESOURCE] Acquired");7879    try { //?try_cleanup80        if (success) { //?check_success81            System.out.println("  [OPERATION] Success");82        } else { //?operation_fail83            System.out.println("  [OPERATION] About to fail...");84            throw new RuntimeException("Operation failed"); //?throw_exception85        }86    } catch (RuntimeException e) { //?catch_cleanup87        System.out.println("  [ERROR] " + e.getMessage());88    } finally { //?finally_cleanup_block89        // Always release the resource90        System.out.println("  [RESOURCE] Released (finally)"); //?release_resource91    }92}9394static int calculateWithReturn(int a, int b) { //?return_method95    try { //?try_return96        int result = a / b; //?calc_return97        System.out.println("  Calculation successful");98        return result; //?return_success99    } catch (ArithmeticException e) { //?catch_return100        System.out.println("  Calculation failed");101        return -1; //?return_error102    } finally { //?finally_return_block103        // This runs BEFORE the return!104        System.out.println("  Finally block executed"); //?finally_before_return105    }
    output  Finally block executed
    Result: -1
    
    --- Try-Finally (no catch) ---
  23. try

    56try { //?try_only57    System.out.println("Performing operation...");58    // Operations here
    outputPerforming operation...
  24. 58    // Operations here59} finally { //?finally_only60    System.out.println("Cleanup runs even without catch block");61}
    outputCleanup runs even without catch block
  25. System.out.println(" === Key Points ===");

    63    System.out.println("\n=== Key Points ===");64    System.out.println("""65        1. finally ALWAYS executes66        2. Executes after try OR after catch67        3. Use for cleanup: close files, release resources68        4. finally runs even if return in try/catch69        5. Can have try-finally without catch70        """);71}
    output
    === Key Points ===
    1. finally ALWAYS executes
    2. Executes after try OR after catch
    3. Use for cleanup: close files, release resources
    4. finally runs even if return in try/catch
    5. Can have try-finally without catch

finally { cleanup } runs whether exception occurred or not.

finally Cleanup code that always runs. Close resources, release locks.

Exercise: Practical.java

Build a robust file reader with complete exception handling