Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Java try-with-resources Statement

Java try-with-resources Statement

Java 9 New Features Java 9 New Features

try-with-resources is a concise resource management approach introduced in Java 7, suitable for resources that need to be closed automatically after use (such as files, database connections, network connections, etc.).

try-with-resources makes it easy to close the resources used in a try-catch block; a so-called resource is an object that must be closed after the program finishes.

The try-with-resources statement ensures that each resource is closed at the end of the statement.

Any object that implements the java.lang.AutoCloseable interface (which includes all objects implementing java.io.Closeable) can be used as a resource.

Advantages:

Execution flow

The key to understanding try-with-resources is to grasp the lifecycle of resources and where control flow goes when an exception occurs.

Basic Syntax

The try-with-resources syntax is as follows:



try (ResourceType resource = new ResourceType()) {

    // Use resources

} catch (ExceptionType e) {

    // Handle exceptions

}

Resources declared in the try block are closed automatically after the code finishes executing, and are even closed safely when an exception occurs.

Multi-resource management (closed in reverse order of declaration):



try (Connection  conn = DriverManager.getConnection(url);

     Statement  stmt = conn.createStatement();

     ResultSet  rs   = stmt.executeQuery(sql)) {



    while (rs.next()) {

        System.out.println(rs.getString(1));

    }

} catch (SQLException e) {

    e.printStackTrace();

}

Closing order:

rs → stmt → conn(声明顺序的逆序)

**Closing order:** multiple resources are closed in the reverse of their declaration order, i.e. resources declared later are closed first. This matches stack-style (LIFO) management and ensures that dependent resources are released correctly.

Declare / initialize res1 Connection ① res2 Statement ② res3 ResultSet Executing try { ... } Automatic close (reverse order) close res3 ResultSet close res2 Statement close res1 Connection ③ ④ ⑤ try block ends

Using the AutoCloseable interface

Any custom class that wants to be managed by try-with-resources only needs to implement the java.lang.AutoCloseable (or java.io.Closeable) interface and implement its close() method.

Example

public

class

DatabaseConnection

implements

AutoCloseable

{

   

private

final

String

url

;

   

public

DatabaseConnection

(

String

url

)

{

       

this

.

url

=

url

;

       

System

.

out

.

println

(

"Connection established: "

url

)

;

   

}

   

public

void

query

(

String

sql

)

{

       

System

.

out

.

println

(

"Executing query: "

sql

)

;

   

}

    @Override

   

public

void

close

(

)

{

       

System

.

out

.

println

(

"Connection closed: "

url

)

;

       

// Release the underlying connection resources...

   

}

}

// Use

try

(

DatabaseConnection db

=

new

DatabaseConnection

(

"jdbc:mysql://localhost/mydb"

)

)

{

    db.

query

(

"SELECT * FROM users"

)

;

}

catch

(

Exception

e

)

{

    e.

printStackTrace

(

)

;

}

Output:



连接已建立: jdbc:mysql://localhost/mydb

执行查询: SELECT * FROM users

连接已关闭: jdbc:mysql://localhost/mydb

Exception handling and suppressed exceptions

When both the business logic in the try block and close() throw exceptions, try-with-resources uses a special strategy: the business exception propagates upward as the primary exception, and the exception produced by close() is suppressed and attached to the primary exception, retrievable via getSuppressed().

try { ... } Throws Exception A (business exception) close() Throws Exception B (close exception) Triggers Primary exception Exception A Suppressed exception Exception B addSuppressed() catch (Exception e) Catch primary exception A e.getSuppressed() Get the suppressed Exception B

Example

try

(

ResourceWithException res

=

new

ResourceWithException

(

)

)

{

    res.

doSomething

(

)

;

         

// Throws Exception A (business exception)

}

catch

(

Exception

e

)

{

   

System

.

out

.

println

(

"Primary exception: "

 

e.

getMessage

(

)

)

;

   

for

(

Throwable

s

:

e.

getSuppressed

(

)

)

{

 

// Get Exception B

       

System

.

out

.

println

(

"Suppressed exception: "

s.

getMessage

(

)

)

;

   

}

}

Output:



主异常: Exception in doSomething

抑制异常: Exception in close

Note:In a traditional try-finally, an exception in the finally block overwrites the business exception, causing the original error to be lost. try-with-resources solves this classic pitfall with its suppressed-exception mechanism.

Java 9 enhancement: reusing external variables

Before Java 9, try-with-resources required resources to be re-declared in try().

Java 9 lifts this restriction: as long as the variable is effectively final, it can be referenced directly in try() without re-declaring it.

Java 7 / 8 — must re-declare

BufferedReader

br

=

new

BufferedReader

(

new

StringReader

(

"hello"

)

)

;

try

(

BufferedReader

br1

=

br

)

{

   

// ← must declare a new variable br1

   

System

.

out

.

println

(

br1.

readLine

(

)

)

;

}

Java 9+ — reuse directly

BufferedReader

br

=

new

BufferedReader

(

new

StringReader

(

"hello"

)

)

;

try

(

br

)

{

                         

// ← use br directly, no re-declaration needed

   

System

.

out

.

println

(

br.

readLine

(

)

)

;

}

**effectively final:** a variable that has not been assigned again after initialization; the compiler automatically treats it as final. There is no need to write the final keyword explicitly.

Comparison with try-finally

Dimension try-finally try-with-resources
Amount of code More — close() must be called manually Less — closed automatically
Risk of missing close High — human oversight easily causes resource leaks Zero — guaranteed by the compiler
Multiple resource nesting Nested layers, poor readability Separated by semicolons, flat and clear
Exception handling finally exception overwrites business exception Suppressed-exception mechanism, information fully preserved
Scope of application Any cleanup logic Resources implementing AutoCloseable

try-finally style (verbose and error-prone)

BufferedReader

br

=

null

;

try

{

    br

=

new

BufferedReader

(

new

FileReader

(

"data.txt"

)

)

;

   

String

line

;

   

while

(

(

line

=

br.

readLine

(

)

)

!=

null

)

System

.

out

.

println

(

line

)

;

}

catch

(

IOException

e

)

{

    e.

printStackTrace

(

)

;

}

finally

{

   

if

(

br

!=

null

)

{

             

// also need a null check

       

try

{

br.

close

(

)

;

}

       

// close itself may also throw

       

catch

(

IOException

e

)

{

e.

printStackTrace

(

)

;

}

   

}

}

try-with-resources style (concise and safe)

try

(

BufferedReader

br

=

new

BufferedReader

(

new

FileReader

(

"data.txt"

)

)

)

{

   

String

line

;

   

while

(

(

line

=

br.

readLine

(

)

)

!=

null

)

System

.

out

.

println

(

line

)

;

}

catch

(

IOException

e

)

{

    e.

printStackTrace

(

)

;

}

Common usage scenarios

Classification Commonly used classes/interfaces
📁 File I/O FileInputStream, FileOutputStream, BufferedReader, BufferedWriter, FileChannel
🗄 Database Connection, PreparedStatement, Statement, ResultSet, EntityManager
🌐 Network communication Socket, ServerSocket, HttpURLConnection, InputStream, OutputStream

When handling any resource that needs explicit closing, prefer try-with-resources over try-finally. The compiler guarantees the resource is closed, the code is more concise, and exception information is more complete — it is the best practice for Java resource management.

Java 9 New Features Java 9 New Features