try catch finally

Catching an Exception

Put risky code in try. If an exception happens, control jumps to the matching catch. The finally block always runs, with or without an exception, and is used for clean-up.

Example

public class Main {
    static void divide(int a, int b) {
        try {
            System.out.println("Dividing " + a + " by " + b);
            int result = a / b;
            System.out.println("Result: " + result);
        } catch (ArithmeticException e) {
            System.out.println("Error: " + e.getMessage());
        } finally {
            System.out.println("Done");
        }
    }

    public static void main(String[] args) {
        divide(10, 2);
        divide(10, 0);
        System.out.println("Program continues");
    }
}

Output

Dividing 10 by 2
Result: 5
Done
Dividing 10 by 0
Error: / by zero
Done
Program continues

Multiple catch Blocks and Multi-catch

Example

Catch more specific exceptions first. Use | to handle several types in one block.

public class Main {
    static void process(String value, int index) {
        try {
            int[] data = { 10, 20, 30 };
            int n = Integer.parseInt(value);
            System.out.println("Result: " + data[index] / n);
        } catch (NumberFormatException | ArithmeticException e) {
            System.out.println("Bad number: " + e.getClass().getSimpleName());
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Bad index: " + e.getMessage());
        } catch (Exception e) {            // most general last
            System.out.println("Something else: " + e);
        }
    }

    public static void main(String[] args) {
        process("5", 1);
        process("abc", 1);
        process("0", 1);
        process("2", 7);
    }
}

Output

Result: 4
Bad number: NumberFormatException
Bad number: ArithmeticException
Bad index: Index 7 out of bounds for length 3

Note: Putting catch (Exception e) before a more specific catch is a compile error, because the specific block could never be reached.

finally Always Runs

Example

Even a return inside try runs finally first.

public class Main {
    static String fetch() {
        try {
            System.out.println("Opening connection");
            return "data";
        } finally {
            System.out.println("Closing connection (finally)");
        }
    }

    public static void main(String[] args) {
        System.out.println("Got " + fetch());
    }
}

Output

Opening connection
Closing connection (finally)
Got data