The try-catch-finally statement

index
INTERMEDIATE

Code that can throw a checked exception must either be in a method that is declared to throw that exception, or it must be in the try part of a try-catch-finally statement. Syntax is as follows:

try {
    // ... code that might throw the exception ...
}
catch (SomeExceptionType e) {
    // ... code to handle this exception type ...
}
catch (SomeOtherExceptionType e) {
    // ... code to handle this other exception type ...
}
finally {
    // ... code that is ALWAYS done before leaving...
}

There may be as many catch blocks as desired; the finally block is optional.

Execution is as follows.

The code in the try block is executed.

If the code in the try block completes normally (without an exception or error), the code in the finally clause is executed.

If an exception (any Throwable) occurs while executing the try block, the try block does not complete, and control goes directly to the first catch block that is declared to catch that exception or any subclass of that exception. When the catch block finishes execution, the code in the finally clause is executed.