Multiple catch Blocks and finally

Different problems, different answers

You can add several catch blocks. Java uses the first one that matches:

public class Main {
    static void test(String text, int index) {
        try {
            int[] nums = {10, 20, 30};
            int n = Integer.parseInt(text);
            System.out.println(nums[index] / n);
        } catch (NumberFormatException e) {
            System.out.println("Not a number");
        } catch (ArithmeticException e) {
            System.out.println("Can't divide by zero");
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("No such position");
        }
    }

    public static void main(String[] args) {
        test("5", 1);
        test("abc", 1);
        test("0", 1);
        test("5", 9);
    }
}

Output

4
Not a number
Can't divide by zero
No such position

If two exceptions need the same answer, join them with |: catch (NumberFormatException | ArithmeticException e).

finally: always runs

Code in finally runs whether there was an exception or not. It's used for clean-up, like closing a file:

public class Main {
    static void divide(int a, int b) {
        try {
            System.out.println(a / b);
        } catch (ArithmeticException e) {
            System.out.println("Error!");
        } finally {
            System.out.println("Finished dividing " + a + " by " + b);
        }
    }

    public static void main(String[] args) {
        divide(10, 2);
        divide(10, 0);
    }
}

Output

5
Finished dividing 10 by 2
Error!
Finished dividing 10 by 0

Catching everything

catch (Exception e) catches almost any exception, because they are all children of Exception. Put it last as a safety net.

Common mistake: Don't catch an exception and do nothing (catch (Exception e) { }). The problem is hidden and very hard to find later. At least print a message.

HOME LABS COMMUNITY DASHBOARD