← Back to Chapters

Java finally Block

? Java finally Block

? Quick Overview

The finally block in Java is used to execute important code such as resource cleanup. It always runs whether an exception occurs or not.

? Key Concepts

  • always executes after try / catch
  • Used for closing files, database connections, streams
  • Optional block but highly recommended
  • Executes even if return is used

? Syntax / Theory

The finally block follows try and optional catch blocks. It ensures cleanup code runs reliably.

? View Code Example
// Basic structure of try-catch-finally
try {
System.out.println("Inside try block");
}
catch(Exception e) {
System.out.println("Exception caught");
}
finally {
System.out.println("Finally block always runs");
}

? Code Example(s)

? View Code Example
// Example showing finally execution even with exception
public class FinallyDemo {
public static void main(String[] args) {
try {
int a = 10 / 0;
}
catch(ArithmeticException e) {
System.out.println("Division by zero");
}
finally {
System.out.println("Cleaning up resources");
}
}
}

? Live Output / Explanation

Expected Output

Division by zero
Cleaning up resources

Even though an exception occurs, the finally block executes without fail.

 

? Interactive Flow Diagram

try catch finally

⚡ Interactive Simulator

Experiment with the simulator to prove that finally runs no matter what happens in the try block.

> System ready. Click "Run Code" to start...

? Use Cases

  • Closing database connections
  • Releasing file handles
  • Stopping background threads
  • Logging execution completion

✅ Tips & Best Practices

  • Avoid heavy logic inside finally
  • Never throw exceptions from finally
  • Use it for cleanup, not business logic

? Try It Yourself

  1. Create a file handling program using finally
  2. Add a return statement inside try and observe finally
  3. Test finally with no catch block