[{"data":1,"prerenderedAt":131},["ShallowReactive",2],{"qa-\u002Fjava\u002Fexceptions\u002Ftry-with-resources":3},{"page":4,"siblings":118,"blog":128},{"id":5,"title":6,"body":7,"description":11,"difficulty":14,"extension":15,"framework":16,"frameworkSlug":17,"meta":18,"navigation":19,"order":12,"path":20,"questions":21,"questionsCount":108,"related":109,"seo":110,"seoDescription":111,"stem":112,"subtopic":113,"topic":114,"topicSlug":115,"updated":116,"__hash__":117},"qa\u002Fjava\u002Fexceptions\u002Ftry-with-resources.md","Try With Resources",{"type":8,"value":9,"toc":10},"minimark",[],{"title":11,"searchDepth":12,"depth":12,"links":13},"",2,[],"medium","md","Java","java",{},true,"\u002Fjava\u002Fexceptions\u002Ftry-with-resources",[22,27,31,35,39,43,47,52,56,60,64,68,72,76,80,84,88,92,96,100,104],{"id":23,"difficulty":24,"q":25,"a":26},"what-is-try-with-resources","easy","What is try-with-resources and what problem does it solve?","Try-with-resources (Java 7+) is a `try` statement that **declares one or more\nresources** in parentheses and **closes them automatically** when the block\nfinishes — normally or via an exception. It replaces the error-prone\nmanual-`finally` cleanup pattern, eliminating **resource leaks**.\n\n```java\n\u002F\u002F Automatic: br is closed no matter how the block exits\ntry (BufferedReader br = new BufferedReader(new FileReader(\"a.txt\"))) {\n    return br.readLine();\n}\n```\n\nA resource is anything that must be released — files, sockets, DB connections,\nstreams. Any object that implements **`AutoCloseable`** can be a resource. The\nproblem it solves: developers routinely forgot the `finally` close, nested it\nwrong, or let a `close()` exception swallow the real one.\n",{"id":28,"difficulty":14,"q":29,"a":30},"manual-finally-boilerplate","What did the equivalent cleanup code look like before try-with-resources?","You had to declare the resource **outside** the `try`, close it in a `finally`,\nand null-check because the constructor might have failed. It was verbose and\neasy to get wrong.\n\n```java\nBufferedReader br = null;\ntry {\n    br = new BufferedReader(new FileReader(\"a.txt\"));\n    return br.readLine();\n} finally {\n    if (br != null) br.close();   \u002F\u002F close itself can throw IOException\n}\n```\n\nWith two resources you'd nest two `try\u002Ffinally` blocks (closing the outer one\neven if the inner constructor threw). Try-with-resources collapses all of that\ninto one parenthesized declaration — **less code, no leaks, and correct\nexception handling**.\n",{"id":32,"difficulty":14,"q":33,"a":34},"autocloseable-interface","What is the AutoCloseable interface?","`AutoCloseable` (Java 7, in `java.lang`) is the **single-method interface** that\nmakes a class usable as a try-with-resources resource. Its only method is\n`close()`, declared to throw the broadest checked exception, `Exception`.\n\n```java\npublic interface AutoCloseable {\n    void close() throws Exception;\n}\n```\n\nOnly types implementing `AutoCloseable` (or its subtype `Closeable`) may appear\nin the resource list — anything else is a compile error. The compiler guarantees\n`close()` is invoked when the block exits, so implementing this interface is all\nit takes to plug a custom type into automatic resource management.\n",{"id":36,"difficulty":14,"q":37,"a":38},"closeable-vs-autocloseable","What is the difference between Closeable and AutoCloseable?","`Closeable` (Java 5, in `java.io`) predates try-with-resources and was\n**retrofitted to extend `AutoCloseable`** in Java 7, so every `Closeable` works\nas a resource. The differences are in the `close()` contract:\n\n| | `AutoCloseable` | `Closeable` |\n| --- | --- | --- |\n| Package | `java.lang` | `java.io` |\n| `close()` throws | `Exception` (broad) | `IOException` (narrow) |\n| Idempotent? | not required | **required** — repeat calls have no effect |\n| Use for | any resource | I\u002FO streams |\n\n```java\npublic interface Closeable extends AutoCloseable {\n    void close() throws IOException;\n}\n```\n\nPrefer implementing `Closeable` when your resource is I\u002FO-related, and\n`AutoCloseable` for everything else (e.g. a lock or a transaction).\n",{"id":40,"difficulty":14,"q":41,"a":42},"close-method-signature","Why does AutoCloseable.close() declare a broader exception than Closeable.close()?","`AutoCloseable` is the **general** abstraction, so its `close()` throws\n`Exception` to allow any resource — a DB connection, a JNI handle — to report\nwhatever failure it has. `Closeable` is **I\u002FO-specific**, so it narrows to\n`IOException`, which is more precise for stream code.\n\n```java\n\u002F\u002F AutoCloseable: may throw any checked exception\nvoid close() throws Exception;\n\u002F\u002F Closeable: I\u002FO resources, narrower contract\nvoid close() throws IOException;\n```\n\nAn implementation can always **narrow** the declared exception (override\n`throws Exception` with `throws IOException`, or `throws` nothing at all).\nThrowing nothing is encouraged: a `close()` that can't fail is far easier to use\nsafely.\n",{"id":44,"difficulty":14,"q":45,"a":46},"idempotent-close","What does it mean that Closeable.close() must be idempotent?","**Idempotent** means calling `close()` a second (or third) time has **no\nadditional effect** and doesn't throw. `Closeable` mandates this; `AutoCloseable`\nonly *recommends* it.\n\n```java\nReader r = new FileReader(\"a.txt\");\nr.close();\nr.close();   \u002F\u002F safe — Closeable.close() is idempotent, does nothing\n```\n\nIt matters because a resource can be closed both **explicitly** in your code and\n**automatically** by try-with-resources, and you don't want the second close to\nblow up. When you write your own `close()`, guarding it with a `boolean closed`\nflag makes it idempotent.\n",{"id":48,"difficulty":49,"q":50,"a":51},"compiler-desugaring","hard","How does the compiler translate try-with-resources?","The compiler **desugars** it into an ordinary `try\u002Ffinally` with the close call\nand **suppressed-exception bookkeeping** baked in. Roughly:\n\n```java\n\u002F\u002F try (Resource r = ...) { body }\n\u002F\u002F becomes:\nResource r = ...;\nThrowable primary = null;\ntry {\n    body;\n} catch (Throwable t) {\n    primary = t;\n    throw t;\n} finally {\n    if (r != null) {\n        if (primary != null) {\n            try { r.close(); }\n            catch (Throwable sup) { primary.addSuppressed(sup); }\n        } else {\n            r.close();   \u002F\u002F body succeeded; let close throw normally\n        }\n    }\n}\n```\n\nSo `close()` is in a generated `finally`, but unlike hand-written `finally` it\nrecords a `close()` failure as a **suppressed** exception instead of discarding\nthe original. That bookkeeping is the whole point.\n",{"id":53,"difficulty":14,"q":54,"a":55},"close-ordering","In what order are multiple resources closed?","In the **reverse order of declaration** — last declared is closed first. This\nmirrors how dependencies stack: a later resource often depends on an earlier\none, so it must be torn down first (like nested `finally` blocks).\n\n```java\ntry (Resource a = new Resource(\"A\");\n     Resource b = new Resource(\"B\");\n     Resource c = new Resource(\"C\")) {\n    \u002F\u002F ... use a, b, c\n}\n\u002F\u002F close order: C, then B, then A\n```\n\nThis LIFO order is guaranteed by the spec. For example, a `BufferedWriter`\nwrapping a `FileWriter` is closed before the `FileWriter` it depends on.\n",{"id":57,"difficulty":24,"q":58,"a":59},"multiple-resources","How do you manage multiple resources in one try-with-resources statement?","Declare them in the parentheses **separated by semicolons**; each is closed\nautomatically. This avoids the deeply nested `try\u002Ffinally` blocks the old style\nrequired.\n\n```java\ntry (FileInputStream in = new FileInputStream(\"src.txt\");\n     FileOutputStream out = new FileOutputStream(\"dst.txt\")) {\n    in.transferTo(out);\n}   \u002F\u002F out closed first, then in — both guaranteed\n```\n\nEach resource is **independently closed**: even if closing `out` throws, the\nruntime still closes `in`. A trailing semicolon after the last resource is\nallowed but optional.\n",{"id":61,"difficulty":49,"q":62,"a":63},"suppressed-exceptions","What are suppressed exceptions?","When the `try` **body throws** and a resource's `close()` **also throws**,\ntry-with-resources **propagates the body's exception** (the more useful one) and\nattaches the `close()` exception to it as a **suppressed** exception, retrievable\nvia `Throwable.getSuppressed()`.\n\n```java\ntry (var r = new FlakyResource()) {\n    throw new RuntimeException(\"body failed\");   \u002F\u002F primary\n}   \u002F\u002F r.close() throws too -> attached as suppressed\n\n\u002F\u002F caught primary:\ncatch (Exception e) {\n    for (Throwable s : e.getSuppressed())\n        System.out.println(\"suppressed: \" + s);  \u002F\u002F close's exception\n}\n```\n\nSo no exception is lost: the primary surfaces, the secondary rides along. The\nstack trace prints suppressed ones under a `Suppressed:` heading.\n",{"id":65,"difficulty":49,"q":66,"a":67},"lost-exception-finally-bug","How does try-with-resources fix the \"lost exception\" bug of try\u002Ffinally?","In a hand-written `try\u002Ffinally`, if **both** the body and `close()` throw, the\n`finally`'s exception **replaces** the body's — the original failure is silently\nlost, hiding the real bug.\n\n```java\ntry {\n    throw new RuntimeException(\"REAL cause\");\n} finally {\n    throw new IOException(\"close failed\");  \u002F\u002F this WINS; \"REAL cause\" gone\n}\n```\n\nTry-with-resources reverses the priority: the **body's** exception wins and the\n`close()` exception is recorded as **suppressed** rather than thrown over it. You\nget the genuine cause as the primary, with the cleanup failure preserved\nalongside instead of erased.\n",{"id":69,"difficulty":14,"q":70,"a":71},"get-add-suppressed","What are getSuppressed() and addSuppressed()?","They're the two `Throwable` methods (Java 7) behind the suppressed-exception\nmechanism. `addSuppressed(Throwable)` attaches a secondary exception to a primary\none; `getSuppressed()` returns the array of attached exceptions.\n\n```java\nThrowable[] suppressed = primaryException.getSuppressed();\n\n\u002F\u002F what the compiler-generated finally effectively calls:\nprimaryException.addSuppressed(closeException);\n```\n\nTry-with-resources calls `addSuppressed` for you automatically, but the methods\nare public so you can use them manually. You **can't** suppress a throwable into\nitself, and passing `null` throws `NullPointerException`.\n",{"id":73,"difficulty":14,"q":74,"a":75},"effectively-final-resource","What is the effectively-final resource form added in Java 9?","Before Java 9 you had to **declare** the resource inside the `try` parentheses.\nJava 9 lets you reference an **already-declared variable** there, as long as it's\n`final` or **effectively final** (never reassigned after init).\n\n```java\n\u002F\u002F Java 9+: reuse an existing effectively-final variable\nBufferedReader br = new BufferedReader(new FileReader(\"a.txt\"));\ntry (br) {           \u002F\u002F no re-declaration needed\n    return br.readLine();\n}   \u002F\u002F br still closed automatically\n```\n\nThis avoids awkward redundant declarations like `try (Reader r2 = r1)`. The\nvariable must not be reassigned, or the compiler rejects it — the resource must\nbe stable so the runtime closes the right object.\n",{"id":77,"difficulty":14,"q":78,"a":79},"try-with-catch-finally","Can try-with-resources have catch and finally blocks?","Yes. You can append `catch` and `finally` clauses just like a normal `try`. The\nkey ordering rule: **resources are closed first**, then the `catch`\u002F`finally`\nrun. So a `catch` sees an already-closed resource.\n\n```java\ntry (var conn = open()) {\n    conn.run();\n} catch (SQLException e) {     \u002F\u002F runs AFTER conn is closed\n    log.error(\"db error\", e);\n} finally {\n    System.out.println(\"done\"); \u002F\u002F runs LAST\n}\n```\n\nThis matters because the `catch` can handle exceptions thrown by `close()` too —\nby the time it executes, cleanup is complete and you only deal with what\npropagated out.\n",{"id":81,"difficulty":14,"q":82,"a":83},"writing-custom-autocloseable","How do you write your own AutoCloseable resource?","Implement `AutoCloseable` (or `Closeable`) and put release logic in `close()`.\nMake it **idempotent** and avoid throwing from `close()` where you can.\n\n```java\nclass Timer implements AutoCloseable {\n    private final long start = System.nanoTime();\n    private boolean closed = false;\n    @Override public void close() {     \u002F\u002F narrowed: throws nothing\n        if (closed) return;             \u002F\u002F idempotent guard\n        closed = true;\n        System.out.println(\"took \" + (System.nanoTime() - start) + \"ns\");\n    }\n}\n\ntry (var t = new Timer()) { doWork(); }  \u002F\u002F prints elapsed time on exit\n```\n\nThis pattern is great for scoped concerns — timing, locks, transaction commit,\nMDC context — anything with a clear \"enter then guaranteed exit.\"\n",{"id":85,"difficulty":49,"q":86,"a":87},"close-throws-exception","What happens if close() throws and the body completes normally?","If the body finishes **without** an exception, there's no primary exception to\nsuppress against, so the `close()` exception is **thrown normally** out of the\n`try` statement. It becomes the exception the caller sees.\n\n```java\ntry (var r = new FlakyResource()) {\n    \u002F\u002F body succeeds, no exception here\n}   \u002F\u002F but close() throws IOException -> THIS propagates to the caller\n```\n\nSo a successful body can still produce a failure from cleanup — which is why\n`close()` on something like a `BufferedWriter` (which flushes) genuinely matters:\na failed final flush surfaces as a real, non-suppressed exception you must handle.\n",{"id":89,"difficulty":14,"q":90,"a":91},"closed-on-return","Are resources closed if the body returns early or throws?","Yes — **every** exit path closes the resources: a normal fall-through, an early\n`return`, a `break`\u002F`continue` out of the block, or a thrown exception. That\nguarantee is the entire value proposition; closing happens in the\ncompiler-generated `finally`.\n\n```java\nString first(BufferedReader br) throws IOException {\n    try (br) {\n        return br.readLine();   \u002F\u002F br is STILL closed before returning\n    }\n}\n```\n\nJust like a `finally`, the close runs before the method actually returns or the\nexception escapes. There's no code path that can leak the resource.\n",{"id":93,"difficulty":49,"q":94,"a":95},"constructor-throws","What happens if a later resource's constructor throws during initialization?","Resources are initialized **left to right**. If a later resource's constructor\nthrows, the resources **already opened are closed** (in reverse order) before the\nexception propagates — no leak.\n\n```java\ntry (Resource a = new Resource(\"A\");      \u002F\u002F opens OK\n     Resource b = openThatThrows();        \u002F\u002F throws here\n     Resource c = new Resource(\"C\")) {     \u002F\u002F never created\n    ...\n}\n\u002F\u002F a IS closed; c was never opened; the constructor's exception propagates\n```\n\nThis is exactly what the nested-`try\u002Ffinally` style struggled to get right by\nhand. The runtime closes only what was successfully created, in LIFO order.\n",{"id":97,"difficulty":14,"q":98,"a":99},"vs-try-finally-table","Compare try-with-resources with try\u002Ffinally.","Try-with-resources is the modern replacement; reach for manual `try\u002Ffinally`\nonly for cleanup that **isn't a closeable resource**.\n\n| Aspect | try-with-resources | try\u002Ffinally |\n| --- | --- | --- |\n| Closes resource | automatic | manual `close()` |\n| Both throw | body wins, close **suppressed** | finally wins, body **lost** |\n| Null safety | handled by compiler | manual null check |\n| Multiple resources | one statement, LIFO | nested blocks |\n| Requires | `AutoCloseable` type | any cleanup code |\n\n```java\ntry (var r = open()) { use(r); }    \u002F\u002F preferred for resources\n```\n\nUse `try\u002Ffinally` for non-resource teardown (resetting a flag, restoring thread\nstate); use try-with-resources for anything implementing `AutoCloseable`.\n",{"id":101,"difficulty":14,"q":102,"a":103},"null-resource","What happens if a resource expression evaluates to null?","Nothing breaks. The generated code **null-checks** each resource before calling\n`close()`, so a `null` resource is simply skipped — no `NullPointerException` at\nclose time.\n\n```java\ntry (Reader r = mightReturnNull()) {   \u002F\u002F returns null\n    if (r != null) r.read();           \u002F\u002F your own guard still needed for use\n}   \u002F\u002F close() is NOT called on null — safe\n```\n\nNote the guard only protects the **close**, not your use of the resource inside\nthe body — dereferencing a `null` `r` there still throws. This null-tolerance is\none of the boilerplate cases the old manual `if (x != null) x.close()` pattern\nhad to handle by hand.\n",{"id":105,"difficulty":49,"q":106,"a":107},"lock-pattern","Why is try-with-resources not a drop-in replacement for lock\u002Funlock?","A `Lock` is **not** `AutoCloseable`, and more importantly the lock must be\n**acquired before** the `try`, not in it — otherwise a failure to acquire would\nstill trigger an unlock. The correct idiom keeps `lock()` outside and `unlock()`\nin a `finally`.\n\n```java\nlock.lock();                  \u002F\u002F acquire BEFORE try\ntry {\n    criticalSection();\n} finally {\n    lock.unlock();            \u002F\u002F try\u002Ffinally, NOT try-with-resources\n}\n```\n\nYou *can* wrap a lock in a small `AutoCloseable` helper that unlocks in `close()`,\nbut you must still acquire before entering the `try`. This is a classic interview\n\"when is try-with-resources the wrong tool\" question — its answer is **manual\nacquisition + try\u002Ffinally**.\n",21,null,{"description":11},"Java try-with-resources interview questions — AutoCloseable and Closeable, automatic resource management, suppressed exceptions, close ordering, the effectively-final form, and comparison with finally.","java\u002Fexceptions\u002Ftry-with-resources","try-with-resources","Exceptions","exceptions","2026-06-20","V4eaAnIVzYq7xnljOMwEir2Z06qpo3K1NxGnW9cJ1RQ",[119,123,124],{"subtopic":120,"path":121,"order":122},"Exception Handling","\u002Fjava\u002Fexceptions\u002Fexception-handling",1,{"subtopic":113,"path":20,"order":12},{"subtopic":125,"path":126,"order":127},"Custom Exceptions","\u002Fjava\u002Fexceptions\u002Fcustom-exceptions",3,{"path":129,"title":130},"\u002Fblog\u002Fjava-try-with-resources","Java Try-With-Resources — Automatic Resource Management Explained",1782244116731]