Challenge 3: try-with-resources Closing Even When an Exception Is Thrown — Possible Solution ==================================================================== NoisyResource.java: public class NoisyResource implements AutoCloseable { @Override public void close() { System.out.println("close() called."); } } TryWithResourcesDemo.java: public class TryWithResourcesDemo { public static void main(String[] args) { try (NoisyResource r = new NoisyResource()) { System.out.println("Inside the try block."); throw new RuntimeException("Something went wrong!"); } catch (RuntimeException e) { System.out.println("Caught: " + e.getMessage()); } } } Output: Inside the try block. close() called. Caught: Something went wrong! Explanation: NoisyResource implements AutoCloseable, so declaring it inside try(...) makes Java call its close() method automatically once the try block exits -- by normal completion OR by an exception. Here the try block throws a RuntimeException before reaching its end, but close() still runs first, BEFORE the exception propagates out to the surrounding catch block. WHY THIS WORKS AS AN ANSWER ------------------------------ This demonstrates the chapter's own claim that try-with-resources calls close() automatically "even if an exception was thrown above" -- the output order (close() printed before the catch block's message) proves cleanup happens during the try block's exit, not after the exception is already being handled elsewhere.