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
Output:5 finally block is always executed rest of the code...
case 2Program in case exception occured but not handled
Output:finally block is always executed Exception in thread main java.lang.ArithmeticException:/ by zero
case 3Program in case exception occured and handled
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).