Exceptions thrown during execution of the try block can be caught and handled in a catch block. A finally block is guaranteed to be executed, regardless of the cause of exit from the try block, or whether any catch block was executed.
Few points to note:
- For each try block there can be zero or more catch blocks, but only one finally block.
- The catch blocks and the finally block must always appear in conjunction with a try block, and in the right order.
- A try block must be followed by at least one catch block or a finally block must be specified.
Let us try to understand the try-catch-finally flow.
The try block establishes a context for exception handling. Termination of a try block occurs as a result of encountering an exception, or from successful execution of the code in the try block.
The catch blocks are skipped for all normal exits from the try block where no exceptions were raised, and control is transferred to the finally block if one is specified.
For all exits from the try block resulting from exceptions, control is transferred to the catch blocks—if any such blocks are specified—to find a matching catch block.If no catch block matches the thrown exception, control is trans- ferred to the finally block if one is specified.
The finally Block
The finally block is guaranteed to be executed, regardless of whether any catch block was executed. Since the finally block is always executed, the finally block can be used to specify any clean-up code (e.g., to free resources such as files,database connections).
Let us consider the following three scenarios:
1. No Exception is thrown
2. Exception is thrown and handled
3. Exception is thrown and not handled