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

Exceptions Thrown from finally Blocks

Learn what happens when exceptions are thrown inside finally blocks and how they mask previous exceptions.

Exceptions Thrown from finally Blocks

What you'll learn: You'll discover what happens when a finally block throws an exception and how it can completely hide earlier exceptions.

The Dangerous Side of finally

You've learned that finally blocks always execute, even when exceptions occur. But what if the finally block itself throws an exception? This creates a surprising and potentially dangerous situation: the new exception from finally replaces any exception that was already in flight.

Think of it like dropping a package while rushing to close a door. If you injure yourself closing the door, everyone focuses on your injury and forgets about the dropped package entirely. The original problem vanishes from sight.

How Exception Masking Works

When a try or catch block throws an exception and then the finally block throws a different exception, Java discards the original exception completely. Only the exception from finally propagates upward. This is called exception masking, and it's a common source of confusion and lost debugging information.

try {
    System.out.println("About to throw");
    throw new RuntimeException("Original problem");
} finally {
    System.out.println("Finally block executing");
    throw new RuntimeException("Finally problem");
}
// Only "Finally problem" is thrown; "Original problem" is lost forever

The original exception—the one that might contain crucial debugging information—disappears without a trace.

Why This Matters

Exception masking makes debugging extremely difficult. Imagine your code fails to close a database connection (throwing an exception in finally), masking the real business logic error that occurred first. You'll chase the wrong problem entirely.

Key Takeaway: Exceptions thrown from finally blocks mask any previous exceptions from the try or catch blocks, causing the original exception to be completely lost—a dangerous situation that hides the root cause of failures.