![]() |
VOOZH | about |
The finally block in java is used to put important codes such as clean up code e.g. closing the file or closing the connection. The finally block executes whether exception rise or not and whether exception handled or not. A finally contains all the crucial statements regardless of the exception occurs or not.
There are 3 possible cases where finally block can be used:
Case 1: When an exception does not rise
In this case, the program runs fine without throwing any exception and finally block execute after the try block.
inside try block 17 finally : i execute always.
Case 2: When the exception rises and handled by the catch block
In this case, the program throws an exception but handled by the catch block, and finally block executes after the catch block.
inside try block catch : exception handled. finally : i execute always.
Case 3: When exception rise and not handled by the catch block
In this case, the program throws an exception but not handled by catch so finally block execute after the try block and after the execution of finally block program terminate abnormally, But finally block execute fine.
Output
Inside try block finally : i will execute always. Exception in thread "main" java.lang.ArithmeticException: / by zero at GFG.main(File.java:10)