It was introduced because of some resources used in Java (like SQL connections or streams) being difficult to be handled properly; as an example, in java 6 to handle a InputStream properly you had to do something like:

InputStream stream = new MyInputStream(...);
try {
    // ... use stream
} catch(IOException e) {
   // handle exception
} finally {
    try {
        if(stream != null) {
            stream.close();
        }
    } catch(IOException e) {
        // handle yet another possible exception
    }
}

Do you notice that ugly double try? now with try-with-resources you can do this:

try (InputStream stream = new MyInputStream(...)){
    // ... use stream
} catch(IOException e) {
   // handle exception
}

and close() is automatically called, if it throws an IOException, it will be supressed (as specified in the Java Language Specification 14.20.3) . Same happens for java.sql.Connection

Answer from morgano on Stack Overflow
🌐
GeeksforGeeks
geeksforgeeks.org › java › try-with-resources-feature-in-java
Try-with-resources Feature in Java - GeeksforGeeks
July 23, 2025 - For try-with-resources, if an exception is thrown in a try block and in a try-with-resources statement, then the method returns the exception thrown in the try block. The exceptions thrown by try-with-resources are suppressed, i.e. we can say ...
🌐
Oracle
docs.oracle.com › javase › tutorial › essential › exceptions › tryResourceClose.html
The try-with-resources Statement (The Java™ Tutorials > Essential Java Classes > Exceptions)
See Java Language Changes for a ... and removed or deprecated options for all JDK releases. The try-with-resources statement is a try statement that declares one or more resources....
🌐
Baeldung
baeldung.com › home › java › core java › java – try with resources
Java - Try with Resources | Baeldung
May 11, 2024 - Support for try-with-resources — introduced in Java 7 — allows us to declare resources to be used in a try block with the assurance that the resources will be closed after the execution of that block.
🌐
W3Schools
w3schools.com › java › java_try_catch_resources.asp
Java try-with-resources
It is a special form of try that works with resources (like files and streams). The resource is declared inside parentheses try(...), and Java will close it automatically when the block finishes - even if an error occurs.
🌐
Oracle
docs.oracle.com › javase › 8 › docs › technotes › guides › language › try-with-resources.html
The try-with-resources Statement
1 month ago - 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.
Top answer
1 of 7
95

It was introduced because of some resources used in Java (like SQL connections or streams) being difficult to be handled properly; as an example, in java 6 to handle a InputStream properly you had to do something like:

InputStream stream = new MyInputStream(...);
try {
    // ... use stream
} catch(IOException e) {
   // handle exception
} finally {
    try {
        if(stream != null) {
            stream.close();
        }
    } catch(IOException e) {
        // handle yet another possible exception
    }
}

Do you notice that ugly double try? now with try-with-resources you can do this:

try (InputStream stream = new MyInputStream(...)){
    // ... use stream
} catch(IOException e) {
   // handle exception
}

and close() is automatically called, if it throws an IOException, it will be supressed (as specified in the Java Language Specification 14.20.3) . Same happens for java.sql.Connection

2 of 7
19

As stated in the documentation:

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.

The following example reads the first line from a file. It uses an instance of BufferedReader to read data from the file. BufferedReader is a resource that must be closed after the program is finished with it:

static String readFirstLineFromFile(String path) throws IOException {
    try (BufferedReader br =
                   new BufferedReader(new FileReader(path))) {
        return br.readLine();
    }
}

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. Because the BufferedReader instance is declared in a try-with-resource statement, it will be closed regardless of whether the try statement completes normally or abruptly

You can read more from here.

🌐
Tutorialspoint
tutorialspoint.com › java › java_try_with_resources.htm
Java - Try with Resources
The Java try-with-resources statement is a try statement that is used for declaring one or more resources such as streams, sockets, databases, connections, etc. These resources must be closed while the program is being finished.
🌐
Medium
medium.com › @reetesh043 › using-try-with-resources-in-java-simplifying-resource-management-bd9ed8cc8754
Try-With-Resources In Java: Simplifying Resource Management | by Reetesh Kumar | Medium
January 10, 2024 - Try-With-Resources, also known as the “Automatic Resource Management” feature, is a Java construct that simplifies resource management by automatically closing resources when they are no longer needed.
Find elsewhere
🌐
Programiz
programiz.com › java-programming › try-with-resources
Java try-with-resources (With Examples)
Become a certified Java programmer. Try Programiz PRO! ... The try-with-resources statement automatically closes all the resources at the end of the statement. A resource is an object to be closed at the end of the program. ... Note: The try-with-resources statement closes all the resources ...
🌐
Educative
educative.io › answers › what-is-try-with-resources-in-java
What is try-with-resources in Java?
The try-with-resources feature was introduced in the Java 7 version. This feature helps close the resources declared in the try block automatically after the execution of the block is complete.
🌐
Jenkov
jenkov.com › tutorials › java-exception-handling › try-with-resources.html
Java Try With Resources
August 25, 2019 - The Java try with resources construct, AKA Java try-with-resources, is an exception handling mechanism that can automatically close resources like a Java InputStream or a JDBC Connection when you are done with them.
🌐
Medium
medium.com › @ucgorai › what-is-try-with-resources-in-java-630c7f825598
What is try-with-resources in Java? | by Uma Charan Gorai | Medium
November 29, 2024 - The try-with-resources statement is a feature in Java introduced in Java 7. It allows you to automatically manage resources such as streams, files, sockets, and database connections.
🌐
Coding Shuttle
codingshuttle.com › home › handbooks › java programming handbook › try with resources
Try-with-Resources in Java
April 9, 2025 - Try-with-Resources (introduced in Java 7) is a feature that allows automatic closing of resources when they are no longer needed.
🌐
Medium
medium.com › thefreshwrites › how-to-use-try-with-resource-in-java-9c0b4ae48d21
How To Use Try With Resource In Java | Exception Handing | by Mouad Oumous | The Fresh Writes | Medium
February 17, 2024 - The Java try with resources construct, AKA Java try-with-resources, is an exception handling mechanism that can automatically close resources like a Java InputStream or a JDBC Connection when you are done with them.
Top answer
1 of 5
83

The main point of try-with-resources is to make sure resources are closed reliably without possibly losing information.

When you don't use try-with-resources there's a potential pitfall called exception-masking. When code in a try block throws an exception, and the close method in the finally also throws an exception, the exception thrown by the try block gets lost and the exception thrown in the finally gets propagated. This is usually unfortunate, since the exception thrown on close is something unhelpful while the informative one is the one thrown from within the try block. (So instead of seeing the SQLException that tells you which referential integrity constraint was violated, you're shown something like BrokenPipeException where closing the resource failed.)

This exception-masking is an annoying problem that try-with-resources prevents from happening.

As part of making sure exception-masking wouldn't lose important exception information, when try-with-resources was developed they had to decide what to do with the exceptions thrown from the close method.

With try-with-resources, if the try block throws an exception and the close method also throws an exception, then the exception from the close block gets tacked on to the original exception:

... there are situations where two independent exceptions can be thrown in sibling code blocks, in particular in the try block of a try-with-resources statement and the compiler-generated finally block which closes the resource. In these situations, only one of the thrown exceptions can be propagated. In the try-with-resources statement, when there are two such exceptions, the exception originating from the try block is propagated and the exception from the finally block is added to the list of exceptions suppressed by the exception from the try block. As an exception unwinds the stack, it can accumulate multiple suppressed exceptions.

On the other hand if your code completes normally but the resource you're using throws an exception on close, that exception (which would get suppressed if the code in the try block threw anything) gets thrown. That means that if you have some JDBC code where a ResultSet or PreparedStatement is closed by try-with-resources, an exception resulting from some infrastructure glitch when a JDBC object gets closed can be thrown and can rollback an operation that otherwise would have completed successfully.

Without try-with-resources whether the close method exception gets thrown is up to the application code. If it gets thrown in a finally block when the try block throws an exception, the exception from the finally block will mask the other exception. But the developer has the option of catching the exception thrown on close and not propagating it.

2 of 5
9

You missed something, the finally block. The try-with-resouces will make it something like,

FileOutputStream outStream = null;
try {
  outStream = new FileOutputStream("people.bin");
  ObjectOutputStream stream = new ObjectOutputStream(outStream);

  stream.writeObject(jar);
  stream.writeObject(can);

  stream.close();
} catch(FileNotFoundException e) {
    System.out.println("sorry it didn't work out");
} catch(IOException f) {
    System.out.println("sorry it didn't work out");
} finally {
  if (outStream != null) { 
    try { 
      outStream.close(); 
    } catch (Exception e) {
    } 
  }
}

Which means you really wanted something like (never swallow exceptions),

try (FileOutputStream outStream = new FileOutputStream("people.bin");
     ObjectOutputStream stream = new ObjectOutputStream(outStream);) {
  stream.writeObject(jar);
  stream.writeObject(can);
  // stream.close(); // <-- closed by try-with-resources.
} catch(FileNotFoundException e) {
    System.out.println("sorry it didn't work out");
    e.printStackTrace();
} catch(IOException f) {
    System.out.println("sorry it didn't work out");
    e.printStackTrace();
}
🌐
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
Oracle added the try with resources construct to the Java language in 2011 to help guarantee objects such as network sockets, database connections and references to files and folders are cleanly terminated after their use.
Published   March 30, 2022
🌐
Medium
medium.com › @mesfandiari77 › try-catch-vs-try-with-resources-in-java-03f262c571a8
Try-Catch vs. Try-With-Resources in Java | by MEsfandiari | Medium
October 3, 2024 - The primary mechanism for handling ... has been introduced as an improvement for managing resources, particularly when dealing with resources like files, database connections, and streams....
🌐
Medium
medium.com › @AlexanderObregon › javas-try-with-resources-statement-explained-6b0ebf84d582
Java’s try-with-resources Statement Explained | Medium
August 18, 2024 - Java makes sure that both resources are closed in the reverse order of their creation—first br2, then br—regardless of whether the try block completes normally or due to an exception. An essential aspect of the try-with-resources statement is its handling of exceptions.
🌐
Stack Abuse
stackabuse.com › the-try-with-resources-statement-in-java
The try-with-resources Statement in Java
April 5, 2019 - try-with-resources is one of the several try statements in Java, aimed to relieve developers of the obligation to release resources used in a try block. It wa...
🌐
Kansas State University
textbooks.cs.ksu.edu › cc210 › 10-exceptions › 06-java › 06-resources
Try with Resources :: CC 210 Textbook
June 27, 2024 - Video Materials Lastly, Java includes a special type of Try-Catch statement, known as a Try with Resources statement, that can perform some of the work typically handled by the finally block. Try with Resources Let’s look at an example of a Try with Resources statement: import java.util.Scanner; ...