Java Finally block

The finally block in Java is invariably executed irrespective of whether an exception is caught or not. It defines a set of statements that must be executed regardless of any exceptions that may arise within the associated try block. Although it is not obligatory to include a finally block, if present, it will invariably run regardless of whether an exception was thrown and subsequently handled by the try and catch segments of the block.

Syntax:
try { // Code that may throw an exception } catch (ExceptionType exception) { // Exception handling } finally { // Code that always executes, regardless of exceptions // Cleanup operations or resource release }

Here's how the finally block works in different scenarios:

When an exception is not thrown

If no exception occurs within the try block, the code in the finally block is executed immediately after the try block completes. This ensures that the cleanup or resource release code in the finally block is always executed, regardless of whether an exception was thrown or not.

try { // Code that may or may not throw an exception } finally { // Cleanup code or resource release }

When an exception is thrown and caught

If an exception occurs within the try block and is caught by a corresponding catch block, the code in the catch block is executed, followed by the code in the finally block. This ensures that the cleanup code in the finally block is still executed, even if an exception was caught.

try { // Code that may throw an exception } catch (ExceptionType exception) { // Exception handling code } finally { // Cleanup code or resource release }

When an exception is thrown but not caught

If an exception occurs within the try block and is not caught by any catch block, the code in the finally block still executes. However, the exception will propagate further up the call stack after the finally block finishes executing.

try { // Code that may throw an exception } finally { // Cleanup code or resource release }
The finally will always execute unless:
  1. System.exit() is called.
  2. The JVM crashes.
  3. The try{} block never ends (e.g. endless loop).

Conclusion

The finally block is useful for ensuring that critical code, such as closing files, releasing database connections, or releasing system resources, is always executed regardless of the occurrence of exceptions. It helps maintain the program's integrity and ensures proper cleanup even in exceptional scenarios.