Last Updated: 06 March, 2023
Finally is a keyword that is used to create a block that contains a set of crucial statements. Finally block is attached to try-catch blocks.
finally block is always executed, whether an exception occurs or not. Therefore, it contains all the necessary statements that need to be executed, such as closing a connection or closing a file, etc.
Syntax:
Use a try-with-resources statement instead of a finally block when closing a file or otherwise recovering resources. The try-with-resources statement automatically releases system resources when no longer needed.
Example 1 : When an exception does not occur
Output
Executing try block...
Length: 17
Executing finally block...
Rest of the code after try/catch blocks...
Example 2 : When an exception occurs and is handled by the catch block
Output
Executing try block...
Executing catch block...
Exception occured: java.lang.NullPointerException
Executing finally block...
Rest of the code after try/catch blocks...
Example 3 : When an exception occur but not handled by the catch block
Output
Executing try block...
Executing finally block...
Exception in thread "main" java.lang.ArithmeticException: / by zero
at com.javabytechie.exceptionhandling.FinallyBlockExample3.main(FinallyBlockExample3.java:7)
That's all guys, hope this Java article is helpful for you.
Happy Learning... 😀
feedback@javabytechie.com