finally block will be executed whenever try and/or catch ends or return happens in try and/or catch. A try block must be matched by at least one of catch and finally, or both.
finally can ensure proper cleanup are conducted. Without finally, consider the return, continue, or break happens before the cleanup code in catch get executed, or there is no catch with the matched exception type that is thrown by try. In both cases, cleanup code will be passed by and resources is not declaimed. Putting cleanup code in a
finally block is always a good practice, even when no exceptions are anticipated.
But exception thrown in finally will still face the problem faced by a try block without catch. So when exception might be thrown in a code in Finally, we should add try and catch within finally.
However: If the JVM exits while the
catch code is being executed, then the
finally block may not execute. Likewise, if the thread executing the
catch code is interrupted or killed, the
finally block may not execute even though the application as a whole continues.