It enables the use of try-with-resources which is a new feature from Java 7.

Old-school:

InputStream is = null;
try {
    is = ...;
    // do stuff with is...
} catch (IOException e) {
    // handle exception
} finally {
    if (is != null) {
        try {
            is.close();
        } catch (IOException innerE) {
            // Handle exception
        }
    }
}

New-school:

try (InputStream is = ...) {
    // do stuff with is...
} catch (IOException e) {
    // handle exception
}

AutoCloseable objects can be opened in the try-block (within the ()) and will be automatically closed instead of using the finally block as in the code example above.

From the Oracle docs:

The try-with-resources statement is a try statement that declares one or more resources. A resource is an object that must be closed after the program is finished with it. The try-with-resources statement ensures that each resource is closed at the end of the statement. Any object that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable, can be used as a resource.

So, this means that all objects that are AutoCloseable can be used this way which means that e.g. ResultSet and other resources can be used in the try-with-resources way. IMO, this simplifies the coding and readability.

However, readability is not the killer argument for why to use the new way. I believe that it is the simple fact that the resources are automatically closed. When used prior to Java 7 it was possible to forget to do null-checks or to close the underlying resource - try-with-resources is simply less error-prone.

But, with that said. It is not required to use try-with-resources, it is still possible to use it the old-school way even though I would not recommend it due (since it is both verbose and error-prone).

Answer from wassgren on Stack Overflow
🌐
Oracle
docs.oracle.com › javase › tutorial › essential › exceptions › tryResourceClose.html
The try-with-resources Statement (The Java™ Tutorials > Essential Java Classes > Exceptions)
In this example, the resources declared in the try-with-resources statement are a FileReader and a BufferedReader. The declaration statements of these resources appear within parentheses immediately after the try keyword. The classes FileReader and BufferedReader, in Java SE 7 and later, implement ...
🌐
Baeldung
baeldung.com › home › java › core java › java – try with resources
Java - Try with Resources | Baeldung
May 11, 2024 - To construct a custom resource ... the close method: public class MyResource implements AutoCloseable { @Override public void close() throws Exception { System.out.println("Closed MyResource"); } } Resources that were ...
🌐
TheServerSide
theserverside.com › tutorial › Use-try-with-resources-Language-Enhancements-for-the-Java-7-OCPJP-Exam
A simple 'try with resources' in Java example | TheServerSide
As you will see in this try with resources example, Java's automatic resource handling feature enables the JVM to automatically invoke the resource termination routines a developer writes inside an AutoCloseable class' close() method.
Published   March 30, 2022
Top answer
1 of 3
3

It enables the use of try-with-resources which is a new feature from Java 7.

Old-school:

InputStream is = null;
try {
    is = ...;
    // do stuff with is...
} catch (IOException e) {
    // handle exception
} finally {
    if (is != null) {
        try {
            is.close();
        } catch (IOException innerE) {
            // Handle exception
        }
    }
}

New-school:

try (InputStream is = ...) {
    // do stuff with is...
} catch (IOException e) {
    // handle exception
}

AutoCloseable objects can be opened in the try-block (within the ()) and will be automatically closed instead of using the finally block as in the code example above.

From the Oracle docs:

The try-with-resources statement is a try statement that declares one or more resources. A resource is an object that must be closed after the program is finished with it. The try-with-resources statement ensures that each resource is closed at the end of the statement. Any object that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable, can be used as a resource.

So, this means that all objects that are AutoCloseable can be used this way which means that e.g. ResultSet and other resources can be used in the try-with-resources way. IMO, this simplifies the coding and readability.

However, readability is not the killer argument for why to use the new way. I believe that it is the simple fact that the resources are automatically closed. When used prior to Java 7 it was possible to forget to do null-checks or to close the underlying resource - try-with-resources is simply less error-prone.

But, with that said. It is not required to use try-with-resources, it is still possible to use it the old-school way even though I would not recommend it due (since it is both verbose and error-prone).

2 of 3
2

Read the documentation of the try-with-resources feature introduced in Java 7.

The try-with-resources statement is a try statement that declares one or more resources. A resource is an object that must be closed after the program is finished with it. The try-with-resources statement ensures that each resource is closed at the end of the statement. Any object that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable, can be used as a resource.

And the Javadoc of AutoCloseable#close():

Closes this resource, relinquishing any underlying resources. This method is invoked automatically on objects managed by the try-with-resources statement.

This means you can create your own subtypes of AutoCloseable resources and use them in this statement.

🌐
Oracle
docs.oracle.com › javase › 8 › docs › technotes › guides › language › try-with-resources.html
The try-with-resources Statement
March 16, 2026 - In this example, the resource declared in the try-with-resources statement is a BufferedReader. The declaration statement appears within parentheses immediately after the try keyword. The class BufferedReader, in Java SE 7 and later, implements the interface java.lang.AutoCloseable.
🌐
GeeksforGeeks
geeksforgeeks.org › java › try-with-resources-feature-in-java
Try-with-resources Feature in Java - GeeksforGeeks
July 23, 2025 - For example, a File resource or a Socket connection resource. The try-with-resources statement ensures that each resource is closed at the end of the statement execution. If we don’t close the resources, it may constitute a resource leak and ...
🌐
Jenkov
jenkov.com › tutorials › java-exception-handling › try-with-resources.html
Java Try With Resources
August 25, 2019 - This is the try-with-resources construct. The FileInputStream variable is declared inside the parentheses after the try keyword. Additionally, a FileInputStream is instantiated and assigned to the variable. When the try block finishes the FileInputStream will be closed automatically. This is possible because FileInputStream implements the Java interface java.lang.AutoCloseable.
🌐
Medium
medium.com › @AlexanderObregon › javas-try-with-resources-statement-explained-6b0ebf84d582
Java’s try-with-resources Statement Explained | Medium
August 18, 2024 - public interface AutoCloseable { void close() throws Exception; } Any class that implements this interface can be used within a try-with-resources block. Additionally, classes that implement the older Closeable interface can also be used in ...
Find elsewhere
Top answer
1 of 2
6

The point of try-with-resources is that:

  • The opening of the Closeable resource is done in the try statement
  • The use of the resource is inside the try statement's block
  • close() is called for you automatically.

So your suggested code:

try(Closeable c = map.remove(key)) {}

... doesn't satisfy the point of try-with-resource, since you're not using the resource inside the block. Presumably your Closeable is already open before this statement.

I'm guessing that you have some code whereby a bunch of resources are opened, work is done, then they are all closed by working through the map.

This is OK, and sometimes unavoidable. But it's cleaner, where possible, to have open() and close() in the same method, with the close() in a finally block, so that you can see at a glance that every open() has a corresponding close() and you can be sure that the close() is always called.

MyCloseable c = MyCloseable.open(...);
try{
       // do stuff with c;
} finally {
     try {
         c.close();
     } catch (IOException e) {
         // ...
     }
}

Once you've achieved that, try-with-resources just makes things neater:

try(MyCloseable c = MyCloseable.open(...)) {
    // do stuff with c;
}

If your requirements mean you can't get open and close into the same methods, then just stick with an explicit close() and ignore the warning.

2 of 2
3

I would just ignore this warning, If you are managing close operation on your own, then just call close(). Empty try-with-resource looks weird.

Consider to extend Map so close operation will be performed automatically on remove:

public class CloseableMap<K,V extends Closeable> extends HashMap<K,V> {

    @Override
    public R remove(K key) {
        V resource = super.remove(key);
        if (resource != null) {
            resource.close();
        }
        return resource;
    }
}
🌐
JetBrains
jetbrains.com › help › inspectopedia › resource.html
AutoCloseable used without 'try'-with-resources | Inspectopedia Documentation
3 weeks ago - Method calls inside a finally block with 'close' in the name and an AutoCloseable argument will not be ignored. Whether to ignore method references to constructors of resource classes. Whether to ignore methods that return a resource and whose name starts with 'get'. This can reduce false positives because most of the getters do not transfer the ownership of the resource, and their call sites are not responsible for closing the resource. This inspection depends on the Java feature 'Try-with-resources', which is available since Java 7.
🌐
Medium
medium.com › @AlexanderObregon › javas-autocloseable-interface-explained-b853aeb663b1
Java’s AutoCloseable Interface Explained | Medium
November 18, 2024 - By declaring all resources within the same block, developers can maintain a clear and concise cleanup process. The close method can throw exceptions, which are treated as suppressed exceptions if another exception occurs in the try block. Java allows retrieving suppressed exceptions for debugging or logging. class FaultyResource implements AutoCloseable { @Override public void close() throws Exception { throw new Exception("Error closing FaultyResource."); } } public class SuppressedExceptionExample { public static void main(String[] args) { try (FaultyResource resource = new FaultyResource()) { throw new RuntimeException("Initial exception."); } catch (Exception e) { System.out.println("Caught: " + e.getMessage()); for (Throwable t : e.getSuppressed()) { System.out.println("Suppressed: " + t.getMessage()); } } } }
🌐
Programiz
programiz.com › java-programming › try-with-resources
Java try-with-resources (With Examples)
When multiple declarations are made, the try-with-resources statement closes these resources in reverse order. In this example, the PrintWriter object is closed first and then the Scanner object is closed. In Java 7, there is a restriction to the try-with-resources statement.
🌐
Medium
medium.com › @kesamkiran › java-for-beginners-day-30-try-with-resources-autocloseable-handling-resources-safely-java-2652cad55253
try-with-resources in Java, AutoCloseable interface, Java resource management, exception handling best practices | Medium
August 21, 2025 - BufferedReader br = null; try { br = new BufferedReader(new FileReader("transactions.txt")); System.out.println(br.readLine()); } catch (IOException e) { e.printStackTrace(); } finally { if (br != null) { try { br.close(); } catch (IOException ex) { ex.printStackTrace(); } } } 😩 Lots of boilerplate code just to close resources! Java 7+ gave us a cleaner way: try-with-resources.
🌐
GitHub
github.com › TEAMMATES › teammates › issues › 8213
Java: Use Java 7 try-with-resources for AutoCloseable resources · Issue #8213 · TEAMMATES/teammates
December 19, 2017 - try (Scanner sc = new Scanner(new BufferedReader(new FileReader(filePath)))) { return sc.useDelimiter("\\Z").next(); } The benefit is two-fold: makes the code shorter and also closes the linked resources without fail, although admittedly I cannot say for sure what will happen if the resources do leak. There are more than 10 places in the code base where this can be applied. Some common AutoCloseable resources are FileWriter, BufferedWriter, PrintWriter, FileOutputStream, OutputStreamWriter, Scanner, FileReader, BufferedReader, FileInputStream, InputStreamReader...
Author   wkurniawan07
🌐
DZone
dzone.com › coding › java › how to specify multiple resources in a single try-with-resources statement
How to Specify Multiple Resources in a Single Try-With-Resources Statement
August 27, 2018 - Each class implements an AutoCloseable and can be used in conjunction with try-with-resources and will have its close() method called automatically when used correctly with the try-with-resources statement. They are named to reflect that the OuterResource can be instantiated with an instance of the InnerResource. ... package dustin.examples.exceptions; import static java.lang.System.out; public class InnerResource implements AutoCloseable { public InnerResource() { out.println("InnerResource created."); } public InnerResource( final RuntimeException exceptionToThrow) { throw exceptionToThrow != null ?
🌐
Netjstech
netjstech.com › 2015 › 05 › try-with-resources-java7.html
Try-With-Resources in Java With Examples | Tech Tutorials
Like in Java 7 Closeable interface extends AutoCloseable and override the behavior of close method to throw IOException. In the above example BufferedReader class is used which implements the close method of Closeable interface and throw IOException. It is possible to use multiple resources with Java try-with-resources statement, all of them will be closed automatically.
🌐
SEI CERT
wiki.sei.cmu.edu › confluence › display › java › ERR54-J.+Use+a+try-with-resources+statement+to+safely+handle+closeable+resources
ERR54-J. Use a try-with-resources statement to safely handle closeable resources | CERT Secure Coding
Use of the try-with-resources statement is also illustrated in ERR05-J. Do not let checked exceptions escape from a finally block , FIO03-J. Remove temporary files before termination , and FIO04-J. Release resources when they are no longer needed . This noncompliant code example uses an ordinary try - catch - finally block in an attempt to close two resources.
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › lang › AutoCloseable.html
AutoCloseable (Java Platform SE 8 )
March 16, 2026 - This method is invoked automatically on objects managed by the try-with-resources statement. While this interface method is declared to throw Exception, implementers are strongly encouraged to declare concrete implementations of the close method to throw more specific exceptions, or to throw no exception at all if the close operation cannot fail. Cases where the close operation may fail require careful attention by implementers. It is strongly advised to relinquish the underlying resources and to internally mark the resource as closed, prior to throwing the exception.
🌐
GitHub
gist.github.com › 911992 › 60b5997223c09850456cf3b66d71ac4b
java try-with-resources AutoCloseable example · GitHub
java try-with-resources AutoCloseable example · Raw · AutoCloseable_Type.java · This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below.
Top answer
1 of 4
29

I found this answered on the coin-dev mailing list: http://mail.openjdk.java.net/pipermail/coin-dev/2009-April/001503.html

5. Some failures of the close method can be safely ignored (e.g., closing a file that was open for read). Does the construct provide for this?

No. While this functionality seems attractive, it is not clear that it's worth the added complexity. As a practical matter these “harmless exceptions” rarely if ever occur, so a program will be no more robust if these exceptions are ignored. If you feel you must ignore them, there is a workaround, but it isn't pretty:

static void copy(String src, String dest) throws IOException {
    boolean done = false;
    try (InputStream in = new FileInputStream(src)) {
        try(OutputStream out = new FileOutputStream(dest)) {
            byte[] buf = new byte[8192];
            int n;
            while ((n = in.read(buf)) >= 0)
                out.write(buf, 0, n);
        }
        done = true;
    } catch(IOException e) {
        if (!done)
            throw e;
    }
}
2 of 4
26

You could use a decorator pattern here to close the resource quietly:

public class QuietResource<T extends AutoCloseable> implements AutoCloseable{
    T resource;
    public QuietResource(T resource){
        this.resource = resource;
    }
    public T get(){
        return resource;
    }
    @Override
    public void close() {
        try {
            resource.close();
        }catch(Exception e){
            // suppress exception
        }
    }  
}

I'm not personally a fan of the resulting syntax, but maybe this works for you:

public static void test(){
    try(QuietResource<MyResource> qr = new QuietResource<>(new MyResource())){
        MyResource r = qr.get();
        r.read();
    } catch (Exception e) {
        System.out.println("Exception: " + e.getMessage());
    }
}

You can do better if you're willing to limit yourself to dealing with interfaces and leverage a Dynamic Proxy Class:

public class QuietResource<T> implements InvocationHandler {

    private T resource;

    @SuppressWarnings("unchecked")
    public static <V extends AutoCloseable> V asQuiet(V resource){
        return (V) Proxy.newProxyInstance(
                resource.getClass().getClassLoader(),
                resource.getClass().getInterfaces(),
                new QuietResource<V>(resource));
    }

    public QuietResource(T resource){
        this.resource = resource;
    }

    @Override
    public Object invoke(Object proxy, Method m, Object[] args) throws Throwable {
        if(m.getName().equals("close")){
            try {
                return m.invoke(resource, args);
            }catch(Exception e){
                System.out.println("Suppressed exception with message: " + e.getCause().getMessage());
                // suppress exception
                return null;
            }
        }
        return m.invoke(resource, args);
    }
}

Then assuming you have:

public interface MyReader extends AutoCloseable{
    int read();
}

With an actual resource class:

public class MyResource implements MyReader {

    public void close() throws Exception{
        throw new Exception("ha!");
    }

    public int read(){
        return 0;
    }
}

Calling syntax would look like:

public static void test(){
    try(MyReader r = QuietResource.asQuiet(new MyResource())){
        r.read();
    } catch (Exception e) {
        System.out.println("Exception: " + e.getMessage());
    }
}

You can do better than this if you want to start including libraries, like AOP enablers. These solutions, however, will work out of the box with JDK7 and no other dependencies.