Java finally block
- Java finally block is a block that is used to execute important code such as closing connection, stream etc.
- Java finally block is always executed whether exception is handled or not.
- Java finally block follows try or catch block.
- Finally block in java can be used to put “cleanup” code such as closing a file, closing connection etc.
- For each try block there can be zero or more catch blocks, but only one finally block.
NOTE:
- If you don’t handle exception, before terminating the program, JVM executes finally block(if any).
- 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).
Output:
finally trumps return.
0
Code that shows finally runs after return
[ad type=”banner”]Output:
finally block is run before method returns.
1
- From the output, observe that the finally block is executed before control is returned to the “System.out.println(SomeClass.proveIt());” statement – which is why the “1” is output after the “finally block is run before method returns.” text
Unique situations when finally will not run after return
The finally block will not be called after return in unique scenarios:
- if System.exit() is called first,
- if the JVM crashes.
- if there is an infinite loop in the try block
- if the power turns off
return statement in both the finally block and the try block
- If we have a return statement in both the finally block and the try block, then anything that is returned in the finally block will actually override any exception or returned value that is inside the try/catch block.
- Here is an example,
- The code above will actually return the “43” instead of the “7”, because the return value in the finally block (“43”) will override the return value in the try block (“7”).
- if the finally block returns a value, it will override any exception thrown in the try/catch block. Here is an example:
- Running the method above will return a “43” and the exception in the try block will not be thrown.
- So a return statement inside the finally block,should be avoided