Java finally block
The Java finally block is a block that is always executed. It is mainly used to perform some important tasks such as closing connection, stream etc.
Note:Before terminating the program, JVM executes finally block(if any).
Note:finally must be followed by try or catch block.
Why use finally block?
case 1Program in case exception does not occur Test it Now
Output:5 finally block is always executed rest of the code...
case 2Program in case exception occured but not handled Test it Now
Output:finally block is always executed Exception in thread main java.lang.ArithmeticException:/ by zero
case 3Program in case exception occured and handled Test it Now
Output:Exception in thread main java.lang.ArithmeticException:/ by zero finally block is always executed rest of the code...
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 program exits(either by calling System.exit() or by causing a fatal error that causes the process to abort).