Java finally block
Java finally block is a block used to execute important code such as closing the connection, etc.
Java finally block is always executed whether an exception is handled or not. Therefore, it contains all the necessary statements that need to be printed regardless of the exception occurs or not.
The finally block follows the try-catch block.
Flowchart of finally block
Note: If you don't handle the exception, before terminating the program, JVM executes finally block (if any).
Why use Java finally block?
Usage of Java finally
Let's see the different cases where Java finally block can be used.
Case 1: When an exception does not occur
Let's see the below example where the Java program does not throw any exception, and the finally block is executed after the try block.
Case 2: When an exception occurr but not handled by the catch block
Let's see the the fillowing example. Here, the code throws an exception however the catch block cannot handle it. Despite this, the finally block is executed after the try block and then the program terminates abnormally.
Case 3: When an exception occurs and is handled by the catch block
Let's see the following example where the Java code throws an exception and the catch block handles the exception. Later the finally block is executed after the try-catch block. Further, the rest of the code is also executed normally.
Rule: For each try block there can be zero or more catch blocks, but only one finally block.
Note: The finally block will not be executed if the program exits (either by calling System.exit() or by causing a fatal error that causes the process to abort).
Next TopicJava Throw Keyword