TIL: When finally Is Executed
In short, finally overrides some of the “expected” behavior like returning from the try – catch block, allowing you to free up resources / do clean up regardless of whether there was an error or not
No Exception Is Thrown
When the try block completes, the finally block is executed, even if there was no exception:
try {
System.out.println("Inside try");
} finally {
System.out.println("Inside finally");
}
In this example, we aren’t throwing an exception from the try block. Thus, the JVM executes all code in both the try and finally blocks.
This outputs:
Inside try
Inside finally
Exception Is Thrown and Not Handled
If there’s an exception and it is not caught, the finally block is still executed:
try {
System.out.println("Inside try");
throw new Exception();
} finally {
System.out.println("Inside finally");
}
The JVM executes the finally block even in the case of an unhandled exception.
And the output would be:
Inside try
Inside finally
Exception in thread "main" java.lang.Exception
Exception Is Thrown and Handled
If there’s an exception and it is caught by the catch block, the finally block is still executed:
try {
System.out.println("Inside try");
throw new Exception();
} catch (Exception e) {
System.out.println("Inside catch");
} finally {
System.out.println("Inside finally");
}
In this case, the catch block handles the thrown exception, and then the JVM executes the finally block and produces the output:
Inside try
Inside catch
Inside finally
Method Returns from try Block
Even returning from the method will not prevent finally blocks from running:
try {
System.out.println("Inside try");
return "from try";
} finally {
System.out.println("Inside finally");
}
Here, even though the method has a return statement, the JVM executes the finally block before handing the control over to the calling method.
We’ll get the output:
Inside try
Inside finally
Method Returns from catch Block
When the catch block contains a return statement, the finally block is still called:
try {
System.out.println("Inside try");
throw new Exception();
} catch (Exception e) {
System.out.println("Inside catch");
return "from catch";
} finally {
System.out.println("Inside finally");
}
When we throw an exception from the try block, the catch block handles the exception. Though there is a return statement in the catch block, the JVM executes the finally block before handing control over to the calling method, and it outputs:
Inside try
Inside catch
Inside finally
From https://www.baeldung.com/java-finally-keyword