Course contentsShow
← Java
Lesson 733 of 2,87018. Exception Handling FundamentalsFree lesson

The finally Block: Guaranteed Execution

Understand how finally blocks always execute, regardless of whether exceptions occur or are caught.

The finally Block: Guaranteed Execution

What you'll learn: How the finally block ensures certain code runs no matter what happens in your exception handling.

Understanding finally: Your Cleanup Guarantee

The finally block is the third and optional part of Java's try-catch-finally structure. Unlike try (which marks risky code) and catch (which handles exceptions), the finally block has one special job: it always executes, regardless of whether an exception occurs, is caught, or even if the method returns early.

Think of it like a safety net with a guarantee: no matter how you exit the building (through the front door, emergency exit, or even being carried out), you will pass through the final checkpoint.

When finally Executes

The finally block runs in these scenarios:

  • No exception occurs — code flows normally through try, skips catch, runs finally
  • Exception is caught — code throws, jumps to matching catch, then runs finally
  • Exception is not caught — code throws, no matching catch exists, but finally still runs before propagating the exception upward
  • Early return — even if try or catch contains a return statement, finally executes first

Basic Syntax

try {
    // code that may throw exceptions
} catch (ExceptionType e) {
    // handle the exception
} finally {
    // this ALWAYS runs
    // cleanup code goes here
}

You can also use finally without catch:

try {
    // risky code
} finally {
    // guaranteed cleanup
}

Why finally Matters

The finally block is crucial for cleanup operations: closing files, releasing resources, resetting states — anything that must happen regardless of success or failure.

Key Takeaway: The finally block guarantees execution after a try block, making it the perfect place for cleanup code that must run whether exceptions occur or not.