Course contentsShow
← Java
Lesson 1948 of 2,87039. File I/O: Basic Byte StreamsFree lesson

Exception Handling in Try-With-Resources

How try-with-resources preserves the primary exception and attaches suppressed exceptions from close().

Exception Handling in Try-With-Resources

What You'll Learn

You'll understand how try-with-resources preserves the most important exception while keeping track of any additional errors that occur during automatic resource cleanup.

The Core Problem

When working with streams, two things can go wrong: an exception in your main code and an exception when the stream's close() method runs automatically. Which exception should you see? Java's try-with-resources has a smart solution.

How Try-With-Resources Handles Exceptions

The primary exception always wins. If an exception occurs in the try block, that's what gets thrown to your code—even if close() also throws an exception during automatic cleanup.

Think of it like a fire alarm and a leaky pipe: if the building is on fire (primary exception), you need to know about that immediately. The leaky pipe (close exception) is still important, but secondary. Java doesn't hide the pipe leak—it attaches it to the fire alarm report as a "suppressed exception."

The Two Scenarios

  1. Exception in try block only: That exception propagates normally
  2. Exception in try block AND close(): The try-block exception propagates, and the close exception becomes a suppressed exception attached to it

You can retrieve suppressed exceptions using getSuppressed() on the caught exception—they're preserved, not lost.

Why This Matters

Without try-with-resources (using manual finally blocks), the close() exception would replace the original exception, losing valuable debugging information. Try-with-resources ensures you always see the root cause while preserving cleanup errors for complete diagnostics.

Key Takeaway:
Try-with-resources prioritizes exceptions from your main code while preserving any close() exceptions as suppressed exceptions, ensuring no diagnostic information is lost.