Java Language Try ... Catch ... Finally


Example

The try { ... } catch ( ... ) { ... } control structure is used for handling Exceptions.

String age_input = "abc";
try {
    int age = Integer.parseInt(age_input);
    if (age >= 18) {
        System.out.println("You can vote!");
    } else {
        System.out.println("Sorry, you can't vote yet.");
    }
} catch (NumberFormatException ex) {
    System.err.println("Invalid input.  '" + age_input + "' is not a valid integer.");
}

This would print:

Invalid input. 'abc' is not a valid integer.

A finally clause can be added after the catch. The finally clause would always be executed, regardless of whether an exception was thrown.

try { ... } catch ( ... ) { ... } finally { ... }

String age_input = "abc";
try {
    int age = Integer.parseInt(age_input);
    if (age >= 18) {
        System.out.println("You can vote!");
    } else {
        System.out.println("Sorry, you can't vote yet.");
    }
} catch (NumberFormatException ex) {
    System.err.println("Invalid input.  '" + age_input + "' is not a valid integer.");
} finally {
    System.out.println("This code will always be run, even if an exception is thrown");
}

This would print:

Invalid input. 'abc' is not a valid integer.
This code will always be run, even if an exception is thrown