Wrapping Up:
In this comprehensive guide, we’ve delved into the nitty-gritty of Java’s try-with-resources statement, a powerful feature that simplifies resource management and ensures your applications run efficiently and reliably.
We began with the basics, understanding how the try-with-resources statement works and how to use it in simple scenarios. We then delved into more advanced usage, exploring how to use the try-with-resources statement with multiple resources and handle exceptions. We also tackled common challenges you might encounter when using the try-with-resources statement, such as dealing with non-auto-closeable resources and handling multiple exceptions.
Along the way, we examined alternative methods for managing resources in Java, such as using a
finally
block or the
close()
method. We compared these methods with the try-with-resources statement, highlighting the advantages and drawbacks of each approach.
Here’s a quick comparison of the methods we’ve discussed:
Method | Pros | Cons |
Try-With-Resources | Automatic resource management, robust exception handling | Only works with auto-closeable resources |
Finally Block | Works with all resources | More verbose, error-prone |
Close() Method | Straightforward, works with all resources | Manual, doesn’t handle exceptions automatically |
Whether you’re just starting out with Java or you’re looking to level up your resource management skills, we hope this guide has given you a deeper understanding of the try-with-resources statement and its capabilities.
With its automatic resource management and robust exception handling, the try-with-resources statement is a powerful tool for writing cleaner, more reliable Java code. Happy coding!
Troubleshooting Java’s Try-With-Resources
While the try-with-resources statement is a powerful feature in Java, it’s not without its challenges. Let’s explore some common issues you might encounter and how to handle them.
Dealing with Non-Auto-Closeable Resources
The try-with-resources statement works with classes that implement the
AutoCloseable
or
Closeable
interfaces. If you’re working with a resource that doesn’t implement one of these interfaces, you’ll need to manage closing the resource manually.
For example, let’s say you have a hypothetical
NonCloseableResource
class that doesn’t implement
AutoCloseable
:
try { NonCloseableResource ncr = new NonCloseableResource(); // use the resource } finally { ncr.close(); } // Output: // The NonCloseableResource will be closed manually in the finally block.
In this example, we use a
finally
block to ensure that the
NonCloseableResource
is closed properly. This is more manual and error-prone than using a try-with-resources statement, but it’s necessary when working with non-auto-closeable resources.
Handling Exceptions in Try-With-Resources
While the try-with-resources statement handles exceptions automatically, it’s important to understand how this works. If an exception occurs within the try block and another exception occurs while closing the resource, the first exception is caught and any subsequent exceptions are suppressed.
Here’s an example:
try (FailingAutoCloseable fac = new FailingAutoCloseable()) { throw new Exception("Exception from try block"); } catch (Exception e) { System.out.println(e.getMessage()); for (Throwable t : e.getSuppressed()) { System.out.println("Suppressed: " + t.getMessage()); } } // Output: // Exception from try block // Suppressed: Exception from close
In this example,
FailingAutoCloseable
is a hypothetical class that throws an exception when closed. We also throw an exception directly within the try block. The catch block first catches and handles the exception from the try block, then it accesses and prints out the suppressed exception from the
close()
method.
This feature of the try-with-resources statement ensures that you’re aware of all exceptions that occur while working with resources, not just the first one.
Try-with-resources example
The following code uses the AutoCloseable Door class in a try with resources statement:
public class TryWithResourcesExample {public static void main(String[] args) throws Exception {try (Door door = new Door()) {door.swing();} catch (Exception e) { /* do something */ }} finally { /* do something */ }}}
When this try with resources example runs, the output of this code is:
Now the door is swinging. Now the door is closed.
In the code above, here are the steps that make this happen:
- The developer creates and initializes the Door instance in the try with resources block.
- The developer explicitly invokes the swing() method.
- The JVM implicitly calls the close() method after the try block completes.
The close() method is always invoked, regardless of whether a checked or unchecked exception is thrown in one of the try, catch or finally blocks. This simplifies resource management code and makes the application more effective.
The resource referenced by the AutoCloseable object will always be closed if a try with resources statement is used, and potential memory leaks commonly caused by a misallocation of resources are eliminated.
Using Java try-with-resources: A Try Statements Guide
Are you finding it challenging to manage resources in Java? You’re not alone. Many developers grapple with this task, but there’s a feature that can make this process a breeze.
Like a responsible librarian, Java’s try-with-resources statement ensures every borrowed resource is returned properly. It’s a powerful tool that can help you manage resources effectively and avoid common pitfalls associated with resource leaks.
This guide will walk you through this powerful feature, from basic use to advanced techniques. So, let’s dive in and start mastering Java’s try-with-resources!
How to use Java’s try-with-resources statement
To use Java’s try-with-resources language feature, the following rules apply:
- All objects managed by a try with resources statement must implement the AutoCloseable interface.
- Multiple AutoCloseable objects can be created within Java’s try with resources block.
- Objects declared in a try with resources statement have scope within the try block, but not the catch and finally blocks.
- The close() method of objects declared in a try with resources block is invoked regardless of whether an exception is thrown during execution.
- If an exception is thrown in the close() method, it may get categorized as a suppressed exception.
Expanding Your Java Horizons: The Bigger Picture
The try-with-resources statement is not just a neat trick for managing a single file or network connection. It’s a powerful tool that can simplify resource management in larger projects and with various types of resources.
When you’re working with multiple resources, the try-with-resources statement can ensure that each resource is closed properly, even if an exception occurs. This can prevent resource leaks and other issues that can degrade system performance.
Moreover, the try-with-resources statement is closely related to other important concepts in Java, like exception handling and file I/O. By mastering the try-with-resources statement, you’re also getting a deeper understanding of these concepts.
Further Resources for Java’s Try-With-Resources
If you’re interested in learning more about the try-with-resources statement and related concepts, here are some resources that you might find helpful:
- Oracle’s Java Tutorials: These tutorials from Oracle, the creators of Java, provide a comprehensive introduction to many features of the language, including the try-with-resources statement.
-
Baeldung’s Guide to the Try-With-Resources Statement in Java: This guide provides a detailed look at the try-with-resources statement, with lots of examples and explanations.
-
Try-with-Resources Feature in Java by GeeksforGeeks: GeeksforGeeks provides a thorough breakdown and example-driven exploration of the try-with-resources feature in Java.
By exploring these resources and continuing to practice, you can become a master of resource management in Java and write cleaner, more efficient, and more reliable code.
Handling Exceptions in Try-With-Resources
One of the key benefits of using the try-with-resources statement is its robust exception handling. If an exception is thrown within the try block, it’s caught and handled by the catch block. If multiple exceptions are thrown — for example, when multiple resources fail to close — the first exception is caught and the others are suppressed.
Here’s an example:
try (FailingAutoCloseable fac = new FailingAutoCloseable()) { throw new Exception("Exception from try block"); } catch (Exception e) { System.out.println(e.getMessage()); for (Throwable t : e.getSuppressed()) { System.out.println("Suppressed: " + t.getMessage()); } } // Output: // Exception from try block // Suppressed: Exception from close
In this example,
FailingAutoCloseable
is a hypothetical class that throws an exception when closed. We also throw an exception directly within the try block. The catch block first catches and handles the exception from the try block, then it accesses and prints out the suppressed exception from the
close()
method.
This feature of the try-with-resources statement ensures that you’re aware of all exceptions that occur while working with resources, not just the first one.
Ngoại lệ bị bỏ qua
Một ngoại lệ có thể được ném ra từ khối mã lệnh kết hợp với câu lệnh
try
-with-resources. Trong ví dụ
writeToFileZipFileContents
, một ngoại lệ có thể được ném từ khối
try
, và có thể lên đến hai ngoại lệ được ném từ
try
-with-resources khi nó cố đóng các đối tượng
ZipFile
và
BufferedWriter
. Nếu một ngoại lệ được ném từ khối
try
và một hoặc nhiều ngoại lệ được ném từ khối
try
-with-resources thì những ngoại lệ ném từ
try
-with-resources sẽ bị bỏ qua, và ngoại lệ được ném bởi khối là ngoại lệ được ném bởi phương thức
writeToFileZipFileContents
. Bạn có thể lấy những ngoại lệ bị bỏ qua này bằng cách gọi phương thức
Throwable.getSuppressed
từ ngoại lệ được ném ra bởi khối
try
.
Java 9 try-with-resources enhancement
In Java 7, there is a restriction to the
try-with-resources
statement. The resource needs to be declared locally within its block.
try (Scanner scanner = new Scanner(new File("testRead.txt"))) { // code }
If we declared the resource outside the block in Java 7, it would have generated an error message.
Scanner scanner = new Scanner(new File("testRead.txt")); try (scanner) { // code }
To deal with this error, Java 9 improved the
try-with-resources
statement so that the reference of the resource can be used even if it is not declared locally. The above code will now execute without any compilation error.
Java: Câu lệnh try-with-resources
Giải phóng thời gian, khai phóng năng lực
Câu lệnh try-with-resources là câu lệnh
try
dùng để khai báo một hoặc nhiều tài nguyên. Một tài nguyên là một đối tượng trong đó phải được đóng sau khi chương trình kết thúc với nó. Câu lệnh
try
-with-resources đảm bảo rằng mỗi tài nguyên sẽ được đóng ngay khi kết thúc câu lệnh. Bất kỳ đối tượng nào thực thi
java.lang.AutoCloseable
, bao gồm cả những đối tượng thực thi
java.io.Closeable
, thì đều được sử dụng như là một nguồn tài nguyên.
Ví dụ dưới đây đọc dòng đầu tiên từ một tập tin. Nó sử dụng một thể hiện của
BufferedReader
để đọc dữ liệu từ tập tin.
BufferedReader
là một tài nguyên và phải được đóng sau khi chương trình kết thúc với nó:
static String readFirstLineFromFile(String path) throws IOException {try (BufferedReader br = new BufferedReader(new FileReader(path))) {return br.readLine();}}
Trong ví dụ trên, tài nguyên được khai báo trong
try
-with-resources là một
BufferedReader
. Câu lệnh khai báo xuất hiện trong ngoặc đơn ngay sau từ khóa
try
. Lớp
BufferedReader
, từ bản Java SE 7, sẽ thực thi giao diện
java.lang.AutoCloseable
. Vì thể hiện của
BufferedReader
được khai báo trong
try
-with-resources, nên nó sẽ đóng bất kể là câu lệnh
try
hoàn thành một cách bình thường hay đột ngột (như là kết quả của phương thức
BufferedReader.readLine
ném ngoại lệ
IOException
).
Trước Java SE 7, bạn có thể sử dụng khối
finally
để thực hiện điều trên. Ví dụ sau đây sử dụng khối
finally
thay vì câu lệnh
try
-with-resources:
static String readFirstLineFromFileWithFinallyBlock(String path) throws IOException {BufferedReader br = new BufferedReader(new FileReader(path));try {return br.readLine();} finally {if (br != null) br.close();}}
Tuy nhiên, trong ví dụ trên, nếu các phương thức
readLine
và
close
đều ném ngoại lệ, thì phương thức
readFirstLineFromFileWithFinallyBlock
sẽ ném ngoại lệ được ném từ khối
finally
; ngoại lệ được ném từ khối
try
sẽ bị bỏ qua. Ngược lại, trong ví dụ nằm trên ví dụ này thì ở phương thức
readFirstLineFromFile
, nếu ngoại lệ được ném ra từ cả hai khối
try
và
try
-with-resources thì phương thức
readFirstLineFromFile
sẽ ném ngoại lệ được ném từ khối
try
; ngoại lệ được ném từ khối
try
-with-resources sẽ bị bỏ qua. Từ bản Java SE 7 thì bạn có thể truy xuất các ngoại lệ bị bỏ qua, xin xem thêm tại phần Ngoại lệ bị bỏ qua.
Bạn có thể khai báo một hoặc nhiều tài nguyên trong câu lệnh
try
-with-resources. Ví dụ sau lấy tên của các tập tin được đóng gói trong file zip là
zipFileName
và tạo ra một tập tin văn bản có chứa tên của các tập tin này:
public static void writeToFileZipFileContents(String zipFileName, String outputFileName) throws java.io.IOException {
java.nio.charset.Charset charset = java.nio.charset.StandardCharsets.US_ASCII;java.nio.file.Path outputFilePath = java.nio.file.Paths.get(outputFileName);
// Mở file zip và tạo đầu ra với// câu lệnh try-with-resources
try (java.util.zip.ZipFile zf = new java.util.zip.ZipFile(zipFileName);java.io.BufferedWriter writer = java.nio.file.Files.newBufferedWriter(outputFilePath, charset)) {// Liệt kê từng mụcfor (java.util.Enumeration entries = zf.entries(); entries.hasMoreElements();) {// Lấy tên đầu vào và ghi nó tới tập tin đầu raString newLine = System.getProperty(“line.separator”);String zipEntryName = ((java.util.zip.ZipEntry)entries.nextElement()).getName() + newLine;writer.write(zipEntryName, 0, zipEntryName.length());}}}
Trong ví dụ trên, câu lệnh
try
-with-resources chứa hai khai báo được phân cách bằng dấu chấm phẩy:
ZipFile
và
BufferedWriter
. Khi các khối mã trực tiếp sau nó chấm dứt hoặc là bình thường hoặc phát sinh ngoại lệ, thì các phương thức
close
của các đối tượng
BufferedWriter
và
ZipFile
được tự động gọi theo thứ tự này. Lưu ý rằng các phương thức
close
của các nguồn tài nguyên được gọi theo thứ tự ngược.
Ví dụ sau đây sử dụng câu lệnh
try
-with-resources để tự động đóng đối tượng
java.sql.Statement
:
public static void viewTable(Connection con) throws SQLException {
String query = “select COF_NAME, SUP_ID, PRICE, SALES, TOTAL from COFFEES”;
try (Statement stmt = con.createStatement()) {ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {String coffeeName = rs.getString(“COF_NAME”);int supplierID = rs.getInt(“SUP_ID”);float price = rs.getFloat(“PRICE”);int sales = rs.getInt(“SALES”);int total = rs.getInt(“TOTAL”);
System.out.println(coffeeName + “, ” + supplierID + “, ” + price + “, ” + sales + “, ” + total);}} catch (SQLException e) {JDBCTutorialUtilities.printSQLException(e);}}
Tài nguyên
java.sql.Statement
được sử dụng trong ví dụ trên là một phần của JDBC 4.1 và API phiên bản mới.
Lưu ý: Mỗi câu lệnh
try
-with-resources có thể có các khối
catch
và
finally
giống như câu lệnh
try
thông thường. Trong
try
-with-resources thì bất kỳ khối
catch
hay
finally
nào chạy sau các tài nguyên được khai báo thì đều bị đóng.
Try-with-resources
To see how the Java try-with-resources construct work, let us look at a Java try-with-resources example:
private static void printFile() throws IOException { try(FileInputStream input = new FileInputStream(“file.txt”)) { int data = input.read(); while(data != -1){ System.out.print((char) data); data = input.read(); } } }
This try-with-resources example shows how to open a Java FileInputStream
inside a try-with-resources block, read some data from the
FileInputStream
, and have the
FileInputStream
closed automatically once execution leaves the try-with-resources block
(not explicitly visible).
Notice the first line inside the method in the try-with-resources example above:
try(FileInputStream input = new FileInputStream(“file.txt”)) {
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
. All classes implementing this
interface can be used inside the try-with-resources construct.
Suppressed Exceptions
In the above example, exceptions can be thrown from the
try-with-resources
statement when:
-
The file
test.txt
is not found. -
Closing the
BufferedReader
object.
An exception can also be thrown from the
try
block as a file read can fail for many reasons at any time.
If exceptions are thrown from both the
try
block and the
try-with-resources
statement, exception from the
try
block is thrown and exception from the
try-with-resources
statement is suppressed.
Retrieving Suppressed Exceptions
In Java 7 and later, the suppressed exceptions can be retrieved by calling the
Throwable.getSuppressed()
method from the exception thrown by the
try
block.
This method returns an array of all suppressed exceptions. We get the suppressed exceptions in the
catch
block.
catch(IOException e) { System.out.println("Thrown exception=>" + e.getMessage()); Throwable[] suppressedExceptions = e.getSuppressed(); for (int i=0; i
" + suppressedExceptions[i]); } }
Các ngoại lệ bị loại bỏ
Nếu một khối try ném một ngoại lệ và một hoặc nhiều ngoại lệ được ném bởi try-with-resources, các ngoại lệ được ném bởi try-with-resources sẽ bị loại bỏ. Nói cách khác, chúng ta có thể nói, các ngoại lệ được ném bởi try-with-resources là các ngoại lệ bị loại bỏ.
Bạn có thể nhận được những ngoại lệ này bằng cách sử dụng phương thức getSuppress() của lớp Throwable.
Java đã thêm một hàm tạo mới và hai phương thức mới trong lớp Throwable để xử lý các ngoại lệ bị loại bỏ.
Constructor | Mô tả |
protected Throwable (String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) | Nó xây dựng một đối tượng Throwable mới với các thông báo chi tiết được chỉ định, nguyên nhân, kích hoạt hoặc vô hiệu hóa, và có thể ghi stacktrace được kích hoạt hoặc vô hiệu hóa. |
Phương thức | Mô tả |
public final void addSuppressed (Throwable exception) | Nó gắn thêm ngoại lệ được chỉ định cho các trường hợp ngoại lệ bị chặn để phân phối ngoại lệ này. Phương thức này là luồng an toàn và thường được gọi là (tự động và ngầm) bởi câu lệnh try-with-resources. Nó ném các ngoại lệ sau đây: IllegalArgumentException: nếu ngoại lệ có thể ném được, một phép ném không thể ngăn chặn chính nó. NullPointerException: nếu ngoại lệ là null. |
public final Throwable[] getSuppressed() | Nó trả về một mảng chứa tất cả các ngoại lệ đã bị chặn bởi câu lệnh try-with-resources. Nếu không có ngoại lệ nào bị chặn hoặc loại bỏ bị vô hiệu hóa, một mảng trống sẽ được trả về. |
In Java, the try-with-resources statement is a try statement that declares one or more resources. The resource is as an object that must be closed after finishing the program. The try-with-resources statement ensures that each resource is closed at the end of the statement execution. You can pass any object that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable. The following example writes a string into a file. It uses an instance of FileOutputStream to write data into the file. FileOutputStream is a resource that must be closed after the program is finished with it. So, in this example, closing of resource is done by itself try. Output:
Output of file
Output:
You can use catch and finally blocks with try-with-resources statement just like an ordinary try statement. Output:
If a try block throws an exception and one or more exceptions are thrown by the try-with-resources, the exceptions thrown by try-with-resources are suppressed. In other words, we can say, exceptions which are thrown by try-with-resources are suppressed exceptions. You can get these exceptions by using the getSuppress() method of Throwable class. Java added a new constructor and two new methods in Throwable class to deal with suppressed exceptions. Next TopicJava Type Inference for Generics |
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.
Its syntax is:
try (resource declaration) { // use of the resource } catch (ExceptionType e1) { // catch block }
As seen from the above syntax, we declare the
try-with-resources
statement by,
-
declaring and instantiating the resource within the
try
clause. - specifying and handling all exceptions that might be thrown while closing the resource.
Note: The try-with-resources statement closes all the resources that implement the AutoCloseable interface.
Let us take an example that implements the
try-with-resources
statement.
Example 1: try-with-resources
import java.io.*; class Main { public static void main(String[] args) { String line; try(BufferedReader br = new BufferedReader(new FileReader("test.txt"))) { while ((line = br.readLine()) != null) { System.out.println("Line =>"+line); } } catch (IOException e) { System.out.println("IOException in try block =>" + e.getMessage()); } } }
Output if the test.txt file is not found.
IOException in try-with-resources block =>test.txt (No such file or directory)
Output if the test.txt file is found.
Entering try-with-resources block Line =>test line
In this example, we use an instance of BufferedReader to read data from the
test.txt
file.
Declaring and instantiating the BufferedReader inside the
try-with-resources
statement ensures that its instance is closed regardless of whether the
try
statement completes normally or throws an exception.
If an exception occurs, it can be handled using the exception handling blocks or the throws keyword.
Replacing try–catch-finally With try-with-resources
The simple and obvious way to use the new try-with-resources functionality is to replace the traditional and verbose try-catch-finally block.
Let’s compare the following code samples.
The first is a typical try-catch-finally block:
Scanner scanner = null;
try {
scanner = new Scanner(new File("test.txt"));
while (scanner.hasNext()) {
System.out.println(scanner.nextLine());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (scanner != null) {
scanner.close();
}
}
And here’s the new super succinct solution using try-with-resources:
try (Scanner scanner = new Scanner(new File("test.txt"))) {
while (scanner.hasNext()) {
System.out.println(scanner.nextLine());
}
} catch (FileNotFoundException fnfe) {
fnfe.printStackTrace();
}
Here’s where to further explore the Scanner class.
Unpacking Java’s Try-With-Resources
The try-with-resources statement is a remarkable feature in Java that simplifies working with resources such as files, network connections, or database connections. These resources must be closed after use to prevent resource leaks and other potential issues.
In Java, you can use the try-with-resources statement to automatically close these resources. This feature is available from Java 7 onwards.
Here’s a basic example of how the try-with-resources statement works:
try (FileReader fr = new FileReader("file.txt")) { int i; while ((i=fr.read()) !=-1) { System.out.print((char) i); } } catch (IOException e) { e.printStackTrace(); } // Output: // Contents of the file.txt will be printed to the console. The FileReader will be closed automatically after the try block.
In this example, we create a new FileReader instance within the parentheses of the try statement. This FileReader instance is a resource that needs to be closed after use. By declaring the resource within the try block, Java automatically closes the FileReader after the try block is exited, whether by normal execution flow or by an exception being thrown.
The primary advantage of using the try-with-resources statement is that it ensures proper cleanup of resources, reducing the risk of resource leaks. It also makes your code cleaner and easier to read, as you don’t need explicit calls to the close() method in a finally block.
However, it’s important to note that the try-with-resources statement only works with instances of classes that implement the AutoCloseable or Closeable interfaces. If you’re working with a resource that doesn’t implement one of these interfaces, you’ll need to manage closing the resource manually.
Leveraging Try-With-Resources with Multiple Resources
Java’s try-with-resources statement isn’t limited to a single resource. It can handle multiple resources at once, which are closed in the reverse order from which they were created. This ensures that each resource is closed properly, even if an exception occurs.
Let’s look at an example where we read data from one file and write it to another:
try (FileReader fr = new FileReader("input.txt"); FileWriter fw = new FileWriter("output.txt")) { int i; while ((i = fr.read()) != -1) { fw.write(i); } } catch (IOException e) { e.printStackTrace(); } // Output: // The data from 'input.txt' is written into 'output.txt'. Both FileReader and FileWriter will be closed automatically after the try block.
In this example, we’re managing two resources:
FileReader
and
FileWriter
. Both are declared within the try statement and are automatically closed at the end of the statement. If an exception occurs within the try block, both resources are still closed properly.
Troubleshooting Java’s Try-With-Resources
While the try-with-resources statement is a powerful feature in Java, it’s not without its challenges. Let’s explore some common issues you might encounter and how to handle them.
Dealing with Non-Auto-Closeable Resources
The try-with-resources statement works with classes that implement the
AutoCloseable
or
Closeable
interfaces. If you’re working with a resource that doesn’t implement one of these interfaces, you’ll need to manage closing the resource manually.
For example, let’s say you have a hypothetical
NonCloseableResource
class that doesn’t implement
AutoCloseable
:
try { NonCloseableResource ncr = new NonCloseableResource(); // use the resource } finally { ncr.close(); } // Output: // The NonCloseableResource will be closed manually in the finally block.
In this example, we use a
finally
block to ensure that the
NonCloseableResource
is closed properly. This is more manual and error-prone than using a try-with-resources statement, but it’s necessary when working with non-auto-closeable resources.
Handling Exceptions in Try-With-Resources
While the try-with-resources statement handles exceptions automatically, it’s important to understand how this works. If an exception occurs within the try block and another exception occurs while closing the resource, the first exception is caught and any subsequent exceptions are suppressed.
Here’s an example:
try (FailingAutoCloseable fac = new FailingAutoCloseable()) { throw new Exception("Exception from try block"); } catch (Exception e) { System.out.println(e.getMessage()); for (Throwable t : e.getSuppressed()) { System.out.println("Suppressed: " + t.getMessage()); } } // Output: // Exception from try block // Suppressed: Exception from close
In this example,
FailingAutoCloseable
is a hypothetical class that throws an exception when closed. We also throw an exception directly within the try block. The catch block first catches and handles the exception from the try block, then it accesses and prints out the suppressed exception from the
close()
method.
This feature of the try-with-resources statement ensures that you’re aware of all exceptions that occur while working with resources, not just the first one.
Ví dụ 2 – try-with-resources – sử dụng khối lệnh finally
package vn.viettuts; import java.io.FileOutputStream; public class TryWithResources3 { public static void main(String args[]) { try (FileOutputStream fos = new FileOutputStream(“/message3.txt”)) { // ghi data vao file String msg = “Welcome to VietTuts.Vn!”; byte byteArray[] = msg.getBytes(); fos.write(byteArray); System.out.println(“Data duoc ghi vao file thanh cong!”); } catch (Exception exception) { System.out.println(exception); } finally { System.out.println(“Khoi lenh finally duoc thuc thi ” + “sau khi dong resources.”); } } }
Kết quả:
Data duoc ghi vao file thanh cong! Khoi lenh finally duoc thuc thi sau khi dong resources.
TL;DR: How Do I Use the Try-with-Resources in Java?
The try-with-resources statement in Java is a feature that automatically closes resources used within the try block, used with the syntax
try (FileReader fr = new FileReader("file.txt")){}
. This is a powerful tool that can help you manage resources effectively and avoid common pitfalls associated with resource leaks.
Here’s a simple example:
try (FileReader fr = new FileReader("file.txt")) { // use the resource } // Output: // The FileReader will be closed automatically after the try block.
In this example, we create a new FileReader instance within the parentheses of the try statement. This FileReader instance is a resource that needs to be closed after use. By declaring the resource within the try block, Java automatically closes the FileReader after the try block is exited, whether by normal execution flow or by an exception being thrown.
This is just a basic way to use the try-with-resources statement in Java, but there’s much more to learn about managing resources effectively. Continue reading for more detailed explanations and advanced usage scenarios.
Table of Contents
- Unpacking Java’s Try-With-Resources
- Leveraging Try-With-Resources with Multiple Resources
- Handling Exceptions in Try-With-Resources
- Exploring Alternative Methods for Resource Management
- Troubleshooting Java’s Try-With-Resources
- Understanding Resource Management in Java
- Expanding Your Java Horizons: The Bigger Picture
- Wrapping Up:
Các lớp thực thi giao diện AutoCloseable hoặc Closeable
Xem các giao diện Javadoc gồm
AutoCloseable
và
Closeable
cho một danh sách các lớp thực hiện một trong các giao diện này. Giao diện
Closeable
mở rộng từ giao diện
AutoCloseable
. Phương thức
close
của giao diện
Closeable
ném ngoại lệ kiểu
IOException
trong khi phương thức
close
của giao diện
AutoCloseable
ném ngoại lệ kiểu
Exception
. Do đó, các lớp con của
AutoCloseable
có thể ghi đè hành vi này của phương thức
close
để ném ngoại lệ được xác định, chẳng hạn như
IOException
, hoặc không có ngoại lệ nào cả.
Giải phóng thời gian, khai phóng năng lực
Using Java try-with-resources: A Try Statements Guide
Are you finding it challenging to manage resources in Java? You’re not alone. Many developers grapple with this task, but there’s a feature that can make this process a breeze.
Like a responsible librarian, Java’s try-with-resources statement ensures every borrowed resource is returned properly. It’s a powerful tool that can help you manage resources effectively and avoid common pitfalls associated with resource leaks.
This guide will walk you through this powerful feature, from basic use to advanced techniques. So, let’s dive in and start mastering Java’s try-with-resources!
Unpacking Java’s Try-With-Resources
The try-with-resources statement is a remarkable feature in Java that simplifies working with resources such as files, network connections, or database connections. These resources must be closed after use to prevent resource leaks and other potential issues.
In Java, you can use the try-with-resources statement to automatically close these resources. This feature is available from Java 7 onwards.
Here’s a basic example of how the try-with-resources statement works:
try (FileReader fr = new FileReader("file.txt")) { int i; while ((i=fr.read()) !=-1) { System.out.print((char) i); } } catch (IOException e) { e.printStackTrace(); } // Output: // Contents of the file.txt will be printed to the console. The FileReader will be closed automatically after the try block.
In this example, we create a new FileReader instance within the parentheses of the try statement. This FileReader instance is a resource that needs to be closed after use. By declaring the resource within the try block, Java automatically closes the FileReader after the try block is exited, whether by normal execution flow or by an exception being thrown.
The primary advantage of using the try-with-resources statement is that it ensures proper cleanup of resources, reducing the risk of resource leaks. It also makes your code cleaner and easier to read, as you don’t need explicit calls to the close() method in a finally block.
However, it’s important to note that the try-with-resources statement only works with instances of classes that implement the AutoCloseable or Closeable interfaces. If you’re working with a resource that doesn’t implement one of these interfaces, you’ll need to manage closing the resource manually.
Try-with-resources Exception Handling
The exception handling semantics of a Java try-with-resources block vary a bit from the exception handling semantics of a standard Java try-catch-finally block. In most situations the changed semantics will work better for you than the semantics of the original try-catch-finally block, even without you understanding the difference precisely. Even so, it can be a good idea to actually understand what is going on exception handling wise, in the try-with-resources construct. Therefore I will explain the exception handling semantics of the try-with-resources construct here.
If an exception is thrown from within a Java try-with-resources block, any resource opened inside the parentheses of the try block will still get closed automatically. The throwing of the exception will force the execution to leave the try block, and this will force the automatic closing of the resource. The exception thrown from inside the try block will get propagated up the call stack, once the resources have been closed.
Some resources may also throw exceptions when you try to close them. In case a resource throws an exception when you try to close it, any other resources opened within the same try-with-resources block will still get closed. After closing all resources, the exception from the failed close-attempt will get propagated up the call stack. In case multiple exceptions are thrown from multiple resource close attempts, the first exception encountered will be the one propagated up the call stack. The rest of the exceptions will be suppressed.
If an exception is thrown both from inside the try-with-resources block,
and when a resource is closed (when
close()
is called),
the exception thrown inside the try block will be propagated up the call stack.
The exception thrown when the resource was attempted closed will be suppressed.
This is opposite of what happens in a normal try-catch-finally block,
where the last exception encountered is the exception that is propagated up the call stack.
To better understand the exception handling semantics of the Java try-with-resources construct,
let us look at some examples. For these examples I have created the following
AutoClosable
implementation
which I can force to throw exceptions both when used and when attempted closed:
public class AutoClosableResource implements AutoCloseable { private String name = null; private boolean throwExceptionOnClose = false; public AutoClosableResource(String name, boolean throwExceptionOnClose) { this.name = name; this.throwExceptionOnClose = throwExceptionOnClose; } public void doOp(boolean throwException) throws Exception { System.out.println(“Resource ” + this.name + ” doing operation”); if(throwException) { throw new Exception(“Error when calling doOp() on resource ” + this.name); } } @Override public void close() throws Exception { System.out.println(“Resource ” + this.name + ” close() called”); if(this.throwExceptionOnClose){ throw new Exception(“Error when trying to close resource ” + this.name); } } }
First, let us look at a basic example with a single resource in use:
public static void main(String[] args){ try { tryWithResourcesSingleResource(); } catch (Exception e) { e.printStackTrace(); Throwable[] suppressed = e.getSuppressed(); } } public static void tryWithResourcesSingleResource() throws Exception { try(AutoClosableResource resourceOne = new AutoClosableResource(“One”, false)) { resourceOne.doOp(false); } }
In case the second parameter to the
AutoClosableResource
construct was changed to
true
,
it would throw an exception when attempted closed. In that case, the exception thrown when attempted closed will
be propagated up the call stack to the
main()
method where the try-catch block will catch
it. In that case, the
Throwable
array returned from
e.getSuppessed()
will be an empty
array (size of 0).
In case the parameter to
resourceOne.doOp()
was changed to
true
also, the
doOp()
method would throw an exception. In that case, it is this exception that is propagated up the call stack to
the
main()
method. The exception thrown when attempting to close the resource would be available inside
the
Throwable
array returned by
e.getSuppressed()
.
Let us look at an example with two
AutoClosable
resources in use:
public static void main(String[] args){ try { tryWithResourcesTwoResources(); } catch (Exception e) { e.printStackTrace(); Throwable[] suppressed = e.getSuppressed(); System.out.println(“suppressed = ” + suppressed); } } public static void tryWithResourcesTwoResources() throws Exception { try(AutoClosableResource resourceOne = new AutoClosableResource(“One”, true); AutoClosableResource resourceTwo = new AutoClosableResource(“Two”, true) ){ resourceOne.doOp(true); resourceTwo.doOp(false); } }
In the case where only one of the resources throw an exception, either during use or when attempted closed,
the behaviour is the same as when only one resource is used. However, in the example above I have forced
both resources to throw an exception when attempted closed, and the first resource to throw an exception when
used (when
doOp()
is called). In that case, the exception thrown from inside the
try block is propagated up the call stack. The two exceptions thrown when attempting to close the
resources are available in the
Throwable
array returned by
e.getSuppressed()
.
Remember, only a single exception can be thrown inside the try block. As soon as an exception is thrown, the try block code is exited, and the resources attempted closed.
Catch Block
You can add a catch block to a try-with-resources block just like you can to a standard try block. If an exception is thrown from within the try block of a try-with-resources block, the catch block will catch it, just like it would when used with a standard try construct.
Before the catch block is entered, the try-with-resources construct will attempt to close the
resources opened inside the try block. In case an exception is thrown when attempting to close one of
the resources, these exceptions will be available from the exception’s
getSuppressed()
method inside
the catch block. Here is an example of a Java try-with-resources block with a catch
block attached:
try(AutoClosableResource resourceOne = new AutoClosableResource(“One”, true)) { resourceOne.doOp(true); } catch(Exception e) { Throwable[] suppressed = e.getSuppressed(); throw e; }
In the example above, the
AutoClosableResource
is configured to throw an exception both when
doOp()
is called, and when it is attempted closed (via
close()
). The exception thrown
from
doOp()
is caught in the catch block, its
getSuppressed()
method returns
an array with the exception thrown when the resource was attempted closed.
In case that an exception is only thrown when the resource is attempted closed, the catch block will
also catch it. The
getSuppressed()
method of that exception will return an empty array, since no
exceptions where suppressed.
Finally Block
It is also possible to add a finally block to a Java try-with-resources block. It will behave just like a standard finally block, meaning it will get executed as the last step before exiting the try-with-resources block – after any catch block has been executed.
In case you throw an exception from within the finally block of a try-with-resources construct, all previously thrown exceptions will be lost! Here is an example of throwing an exception from within the finally block of a Java try-with-resources construct:
public static void main(String[] args){ try { tryWithResourcesSingleResource(); } catch (Exception e) { e.printStackTrace(); Throwable[] suppressed = e.getSuppressed(); } } public static void tryWithResourcesSingleResource() throws Exception { try(AutoClosableResource resourceOne = new AutoClosableResource(“One”, true)) { resourceOne.doOp(false); } catch(Exception e) { Throwable[] suppressed = e.getSuppressed(); throw e; } finally { throw new Exception(“Hey, an exception from the finally block”); } }
Notice, that the exception thrown from within the catch block will be ignored because a new exception is thrown from within the finally block. This would also be true if there was no catch block. Then any exception thrown from inside the try block would get lost because a new exception is thrown from inside the finally block. Any previous exceptions are not suppressed, so they are not available from within the exception thrown from the finally block.
Adding Suppressed Exceptions Manually
The
Throwable
class has a method named
addSuppressed()
which takes a
Throwable
object as parameter. Using the
addSuppressed()
method it is possible to add suppressed exceptions to
another exception, in case you need that. Here is an example that shows how to add suppressed exceptions to a
Java exception manually:
Exception finalException = null; try(AutoClosableResource resourceOne = new AutoClosableResource(“One”, true)) { resourceOne.doOp(false); } catch(Exception e) { finalException = new Exception(“Error…”); finalException.addSuppressed(e); for(Throwable suppressed : e.getSuppressed()){ finalException.addSuppressed(suppressed); } } finally { if(finalException != null){ throw finalException; } }
Notice how the
Throwable
reference has to be declared outside the try-with-resources construct.
Otherwise the catch and finally blocks cannot access it.
In most cases you will not need to add suppressed exceptions to an exception manually, but now you have at least seen how it can be done, in case you ever run into a situation where you need it.
Exploring Alternative Methods for Resource Management
While the try-with-resources statement is a powerful tool in Java, it’s not the only way to manage resources. There are other methods you can use, such as the
finally
block or the
close()
method. Let’s dive into these alternatives and see how they compare.
Using the Finally Block
Before the introduction of the try-with-resources statement in Java 7, developers often used a
finally
block to ensure that resources were closed properly. Here’s an example:
FileReader fr = null; try { fr = new FileReader("file.txt"); int i; while ((i = fr.read()) != -1) { System.out.print((char) i); } } catch (IOException e) { e.printStackTrace(); } finally { if (fr != null) { try { fr.close(); } catch (IOException e) { e.printStackTrace(); } } } // Output: // Contents of the file.txt will be printed to the console. The FileReader will be closed in the finally block.
In this example, we manually close the
FileReader
in the
finally
block. This ensures that the
FileReader
is closed whether an exception occurs or not.
However, this method is more verbose and error-prone than using a try-with-resources statement. You have to remember to close each resource and handle exceptions that might occur during closing.
Using the Close() Method
Another way to manage resources is by calling the
close()
method on the resource. However, this method is manual and doesn’t offer the automatic resource management that try-with-resources provides.
FileReader fr = new FileReader("file.txt"); int i; while ((i = fr.read()) != -1) { System.out.print((char) i); } fr.close(); // Output: // Contents of the file.txt will be printed to the console. The FileReader will be closed manually after use.
In this example, we manually close the
FileReader
after use by calling
fr.close()
. This method is straightforward, but it doesn’t handle exceptions automatically, and it requires you to remember to close each resource.
Overall, while these methods can be useful in some scenarios, the try-with-resources statement is generally the most effective and efficient way to manage resources in Java. It reduces the risk of resource leaks, handles exceptions automatically, and makes your code cleaner and easier to read.
Overview
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.
The resources declared need to implement the AutoCloseable interface.
Find out if it is a bad practice to catch Throwable.
Learn how to globally handle all uncaught exceptions in your Java application
Learn the differences between Java’s checked and unchecked exception with some examples
Java 9 – Effectively Final Variables
Before Java 9, we could only use fresh variables inside a try-with-resources block:
try (Scanner scanner = new Scanner(new File("testRead.txt"));
PrintWriter writer = new PrintWriter(new File("testWrite.txt"))) {
// omitted
}
As shown above, this was especially verbose when declaring multiple resources. As of Java 9 and as part of JEP 213, we can now use final or even effectively final variables inside a try-with-resources block:
final Scanner scanner = new Scanner(new File("testRead.txt"));
PrintWriter writer = new PrintWriter(new File("testWrite.txt"))
try (scanner;writer) {
// omitted
}
Put simply, a variable is effectively final if it doesn’t change after the first assignment, even though it’s not explicitly marked as final.
As shown above, the scanner variable is declared final explicitly, so we can use it with the try-with-resources block. Although the writer variable is not explicitly final, it doesn’t change after the first assignment. So, we can to use the writer variable too.
Conclusion
In this article, we discussed how to use try-with-resources and how to replace try, catch, and finally with try-with-resources.
We also looked at building custom resources with AutoCloseable and the order in which resources are closed.
The complete source code for the example is available in this GitHub project.
The Java Tutorials have been written for JDK 8. Examples and practices described in this page don’t take advantage of improvements introduced in later releases and might use technology no longer available.See Java Language Changes for a summary of updated language features in Java SE 9 and subsequent releases.See JDK Release Notes for information about new features, enhancements, and removed or deprecated options for all JDK releases.
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
FileReader
and
BufferedReader
to read data from the file.
FileReader
and
BufferedReader
are resources that must be closed after the program is finished with it:
static String readFirstLineFromFile(String path) throws IOException { try (FileReader fr = new FileReader(path); BufferedReader br = new BufferedReader(fr)) { return br.readLine(); } }
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 the interface
java.lang.AutoCloseable
. Because the
FileReader
and
BufferedReader
instances are declared in a
try
-with-resource statement, they will be closed regardless of whether the
try
statement completes normally or abruptly (as a result of the method
BufferedReader.readLine
throwing an
IOException
).
Prior to Java SE 7, you can use a
finally
block to ensure that a resource is closed regardless of whether the
try
statement completes normally or abruptly. The following example uses a
finally
block instead of a
try
-with-resources statement:
static String readFirstLineFromFileWithFinallyBlock(String path) throws IOException { FileReader fr = new FileReader(path); BufferedReader br = new BufferedReader(fr); try { return br.readLine(); } finally { br.close(); fr.close(); } }
However, this example might have a resource leak. A program has to do more than rely on the garbage collector (GC) to reclaim a resource’s memory when it’s finished with it. The program must also release the resoure back to the operating system, typically by calling the resource’s
close
method. However, if a program fails to do this before the GC reclaims the resource, then the information needed to release the resource is lost. The resource, which is still considered by the operaing system to be in use, has leaked.
In this example, if the
readLine
method throws an exception, and the statement
br.close()
in the
finally
block throws an exception, then the
FileReader
has leaked. Therefore, use a
try
-with-resources statement instead of a
finally
block to close your program’s resources.
If the methods
readLine
and
close
both throw exceptions, then the method
readFirstLineFromFileWithFinallyBlock
throws the exception thrown from the
finally
block; the exception thrown from the
try
block is suppressed. In contrast, in the example
readFirstLineFromFile
, if exceptions are thrown from both the
try
block and the
try
-with-resources statement, then the method
readFirstLineFromFile
throws the exception thrown from the
try
block; the exception thrown from the
try
-with-resources block is suppressed. In Java SE 7 and later, you can retrieve suppressed exceptions; see the section Suppressed Exceptions for more information.
The following example retrieves the names of the files packaged in the zip file
zipFileName
and creates a text file that contains the names of these files:
public static void writeToFileZipFileContents(String zipFileName, String outputFileName) throws java.io.IOException { java.nio.charset.Charset charset = java.nio.charset.StandardCharsets.US_ASCII; java.nio.file.Path outputFilePath = java.nio.file.Paths.get(outputFileName); // Open zip file and create output file with // try-with-resources statement try ( java.util.zip.ZipFile zf = new java.util.zip.ZipFile(zipFileName); java.io.BufferedWriter writer = java.nio.file.Files.newBufferedWriter(outputFilePath, charset) ) { // Enumerate each entry for (java.util.Enumeration entries = zf.entries(); entries.hasMoreElements();) { // Get the entry name and write it to the output file String newLine = System.getProperty(“line.separator”); String zipEntryName = ((java.util.zip.ZipEntry)entries.nextElement()).getName() + newLine; writer.write(zipEntryName, 0, zipEntryName.length()); } } }
In this example, the
try
-with-resources statement contains two declarations that are separated by a semicolon:
ZipFile
and
BufferedWriter
. When the block of code that directly follows it terminates, either normally or because of an exception, the
close
methods of the
BufferedWriter
and
ZipFile
objects are automatically called in this order. Note that the
close
methods of resources are called in the opposite order of their creation.
The following example uses a
try
-with-resources statement to automatically close a
java.sql.Statement
object:
public static void viewTable(Connection con) throws SQLException { String query = “select COF_NAME, SUP_ID, PRICE, SALES, TOTAL from COFFEES”; try (Statement stmt = con.createStatement()) { ResultSet rs = stmt.executeQuery(query); while (rs.next()) { String coffeeName = rs.getString(“COF_NAME”); int supplierID = rs.getInt(“SUP_ID”); float price = rs.getFloat(“PRICE”); int sales = rs.getInt(“SALES”); int total = rs.getInt(“TOTAL”); System.out.println(coffeeName + “, ” + supplierID + “, ” + price + “, ” + sales + “, ” + total); } } catch (SQLException e) { JDBCTutorialUtilities.printSQLException(e); } }
The resource
java.sql.Statement
used in this example is part of the JDBC 4.1 and later API.
Note: A
try
-with-resources statement can have
catch
and
finally
blocks just like an ordinary
try
statement. In a
try
-with-resources statement, any
catch
or
finally
block is run after the resources declared have been closed.
An exception can be thrown from the block of code associated with the
try
-with-resources statement. In the example
writeToFileZipFileContents
, an exception can be thrown from the
try
block, and up to two exceptions can be thrown from the
try
-with-resources statement when it tries to close the
ZipFile
and
BufferedWriter
objects. If an exception is thrown from the
try
block and one or more exceptions are thrown from the
try
-with-resources statement, then those exceptions thrown from the
try
-with-resources statement are suppressed, and the exception thrown by the block is the one that is thrown by the
writeToFileZipFileContents
method. You can retrieve these suppressed exceptions by calling the
Throwable.getSuppressed
method from the exception thrown by the
try
block.
See the Javadoc of the
AutoCloseable
and
Closeable
interfaces for a list of classes that implement either of these interfaces. The
Closeable
interface extends the
AutoCloseable
interface. The
close
method of the
Closeable
interface throws exceptions of type
IOException
while the
close
method of the
AutoCloseable
interface throws exceptions of type
Exception
. Consequently, subclasses of the
AutoCloseable
interface can override this behavior of the
close
method to throw specialized exceptions, such as
IOException
, or no exception at all.
In Java, the Try-with-resources statement is a try statement that declares one or more resources in it. A resource is an object that must be closed once your program is done using it. 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 also the program could exhaust the resources available to it.
You can pass any object as a resource that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable.
By this, now we don’t need to add an extra finally block for just passing the closing statements of the resources. The resources will be closed as soon as the try-catch block is executed.
Syntax: Try-with-resources
try(declare resources here) {
// use resources
}
catch(FileNotFoundException e) {
// exception handling
}
Exceptions:
When it comes to exceptions, there is a difference in try-catch-finally block and try-with-resources block. If an exception is thrown in both try block and finally block, the method returns the exception thrown in finally block.
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 that try-with-resources block throws suppressed exceptions.
Now, let us discuss both the possible scenarios which are demonstrated below as an example as follows:
- Case 1: Single resource
- Case 2: Multiple resources
Example 1: try-with-resources having a single resource
Understanding Resource Management in Java
Resource management is a critical aspect of programming. In Java, resources are objects that must be closed manually after use. These include system resources like files, network connections, and database connections. Improper management of these resources can lead to resource leaks, which can, in turn, degrade system performance and cause your application to behave unpredictably.
Before Java 7, developers had to close these resources manually, typically in a
finally
block to ensure that the resource was closed whether an exception occurred or not. However, this approach was verbose and error-prone.
Java 7 introduced a new feature to simplify resource management: the try-with-resources statement. This feature is based on the
AutoCloseable
interface, which includes a single method,
close()
, that closes the resource.
public interface AutoCloseable { void close() throws Exception; }
Any class that represents a resource which needs to be closed after use should implement
AutoCloseable
and override its
close()
method. This includes many classes in the Java standard library, like
FileInputStream
,
FileOutputStream
,
PrintWriter
,
Scanner
, and more.
With the try-with-resources statement, you can declare one or more resources within a try block, and Java will automatically close these resources at the end of the block. This feature ensures proper cleanup of resources, reduces the risk of resource leaks, and makes your code cleaner and easier to read.
Advantages of using try-with-resources
Here are the advantages of using try-with-resources:
finally block not required to close the resource
Before Java 7 introduced this feature, we had to use the
finally
block to ensure that the resource is closed to avoid resource leaks.
Here’s a program that is similar to Example 1. However, in this program, we have used finally block to close resources.
Example 2: Close resource using finally block
import java.io.*; class Main { public static void main(String[] args) { BufferedReader br = null; String line; try { System.out.println("Entering try block"); br = new BufferedReader(new FileReader("test.txt")); while ((line = br.readLine()) != null) { System.out.println("Line =>"+line); } } catch (IOException e) { System.out.println("IOException in try block =>" + e.getMessage()); } finally { System.out.println("Entering finally block"); try { if (br != null) { br.close(); } } catch (IOException e) { System.out.println("IOException in finally block =>"+e.getMessage()); } } } }
Output
Entering try block Line =>line from test.txt file Entering finally block
As we can see from the above example, the use of
finally
block to clean up resources makes the code more complex.
Notice the
try...catch
block in the
finally
block as well? This is because an
IOException
can also occur while closing the
BufferedReader
instance inside this
finally
block so it is also caught and handled.
The
try-with-resources
statement does automatic resource management. We need not explicitly close the resources as JVM automatically closes them. This makes the code more readable and easier to write.
try-with-resources with multiple resources
We can declare more than one resource in the
try-with-resources
statement by separating them with a semicolon
Example 3: try with multiple resources
import java.io.*; import java.util.*; class Main { public static void main(String[] args) throws IOException{ try (Scanner scanner = new Scanner(new File("testRead.txt")); PrintWriter writer = new PrintWriter(new File("testWrite.txt"))) { while (scanner.hasNext()) { writer.print(scanner.nextLine()); } } } }
If this program executes without generating any exceptions,
Scanner
object reads a line from the
testRead.txt
file and writes it in a new
testWrite.txt
file.
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.
Resource Closing Order
Resources that were defined/acquired first will be closed last. Let’s look at an example of this behavior:
Resource 1:
public class AutoCloseableResourcesFirst implements AutoCloseable {
public AutoCloseableResourcesFirst() {
System.out.println("Constructor -> AutoCloseableResources_First");
}
public void doSomething() {
System.out.println("Something -> AutoCloseableResources_First");
}
@Override
public void close() throws Exception {
System.out.println("Closed AutoCloseableResources_First");
}
}
Resource 2:
public class AutoCloseableResourcesSecond implements AutoCloseable {
public AutoCloseableResourcesSecond() {
System.out.println("Constructor -> AutoCloseableResources_Second");
}
public void doSomething() {
System.out.println("Something -> AutoCloseableResources_Second");
}
@Override
public void close() throws Exception {
System.out.println("Closed AutoCloseableResources_Second");
}
}
Code:
private void orderOfClosingResources() throws Exception {
try (AutoCloseableResourcesFirst af = new AutoCloseableResourcesFirst();
AutoCloseableResourcesSecond as = new AutoCloseableResourcesSecond()) {
af.doSomething();
as.doSomething();
}
}
Output:
Constructor -> AutoCloseableResources_First
Constructor -> AutoCloseableResources_Second
Something -> AutoCloseableResources_First
Something -> AutoCloseableResources_Second
Closed AutoCloseableResources_Second
Closed AutoCloseableResources_First
Custom AutoClosable Implementations
The Java try-with-resources construct does not just work with Java’s built-in classes.
You can also implement the
java.lang.AutoCloseable
interface in your own classes,
and use them with the try-with-resources construct.
The
AutoClosable
interface only has a single method called
close()
.
Here is how the interface looks:
public interface AutoClosable { public void close() throws Exception; }
Any class that implements this interface can be used with the Java try-with-resources construct. Here is a simple example implementation:
public class MyAutoClosable implements AutoCloseable { public void doIt() { System.out.println(“MyAutoClosable doing it!”); } @Override public void close() throws Exception { System.out.println(“MyAutoClosable closed!”); } }
The
doIt()
method is not part of the
AutoClosable
interface. It is there because
we want to be able to do something more than just closing the object.
Here is an example of how the
MyAutoClosable
is used with the try-with-resources
construct:
private static void myAutoClosable() throws Exception { try(MyAutoClosable myAutoClosable = new MyAutoClosable()){ myAutoClosable.doIt(); } }
Here is the output printed to
System.out
when the method
myAutoClosable()
is called:
MyAutoClosable doing it! MyAutoClosable closed!
As you can see, try-with-resources is a quite powerful way of making sure that resources
used inside a
try-catch
block are closed correctly, no matter if these resources are your
own creation, or Java’s built-in components.
Understanding Resource Management in Java
Resource management is a critical aspect of programming. In Java, resources are objects that must be closed manually after use. These include system resources like files, network connections, and database connections. Improper management of these resources can lead to resource leaks, which can, in turn, degrade system performance and cause your application to behave unpredictably.
Before Java 7, developers had to close these resources manually, typically in a
finally
block to ensure that the resource was closed whether an exception occurred or not. However, this approach was verbose and error-prone.
Java 7 introduced a new feature to simplify resource management: the try-with-resources statement. This feature is based on the
AutoCloseable
interface, which includes a single method,
close()
, that closes the resource.
public interface AutoCloseable { void close() throws Exception; }
Any class that represents a resource which needs to be closed after use should implement
AutoCloseable
and override its
close()
method. This includes many classes in the Java standard library, like
FileInputStream
,
FileOutputStream
,
PrintWriter
,
Scanner
, and more.
With the try-with-resources statement, you can declare one or more resources within a try block, and Java will automatically close these resources at the end of the block. This feature ensures proper cleanup of resources, reduces the risk of resource leaks, and makes your code cleaner and easier to read.
Exploring Alternative Methods for Resource Management
While the try-with-resources statement is a powerful tool in Java, it’s not the only way to manage resources. There are other methods you can use, such as the
finally
block or the
close()
method. Let’s dive into these alternatives and see how they compare.
Using the Finally Block
Before the introduction of the try-with-resources statement in Java 7, developers often used a
finally
block to ensure that resources were closed properly. Here’s an example:
FileReader fr = null; try { fr = new FileReader("file.txt"); int i; while ((i = fr.read()) != -1) { System.out.print((char) i); } } catch (IOException e) { e.printStackTrace(); } finally { if (fr != null) { try { fr.close(); } catch (IOException e) { e.printStackTrace(); } } } // Output: // Contents of the file.txt will be printed to the console. The FileReader will be closed in the finally block.
In this example, we manually close the
FileReader
in the
finally
block. This ensures that the
FileReader
is closed whether an exception occurs or not.
However, this method is more verbose and error-prone than using a try-with-resources statement. You have to remember to close each resource and handle exceptions that might occur during closing.
Using the Close() Method
Another way to manage resources is by calling the
close()
method on the resource. However, this method is manual and doesn’t offer the automatic resource management that try-with-resources provides.
FileReader fr = new FileReader("file.txt"); int i; while ((i = fr.read()) != -1) { System.out.print((char) i); } fr.close(); // Output: // Contents of the file.txt will be printed to the console. The FileReader will be closed manually after use.
In this example, we manually close the
FileReader
after use by calling
fr.close()
. This method is straightforward, but it doesn’t handle exceptions automatically, and it requires you to remember to close each resource.
Overall, while these methods can be useful in some scenarios, the try-with-resources statement is generally the most effective and efficient way to manage resources in Java. It reduces the risk of resource leaks, handles exceptions automatically, and makes your code cleaner and easier to read.
Ví dụ 2 – try-with-resources – sử dụng nhiều resources
package vn.viettuts; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; public class TryWithResources2 { public static void main(String[] args) { // su dung try-with-resources // su dung nhieu resources try (FileOutputStream fos = new FileOutputStream(“/message2.txt”); InputStream is = new FileInputStream(“/message2.txt”)) { // ghi data vao file String msg = “Welcome to VietTuts.Vn!”; byte byteArray[] = msg.getBytes(); fos.write(byteArray); System.out.println(“——-Data da duoc ghi vao file———“); System.out.println(msg); // doc data tu file da ghi DataInputStream inst = new DataInputStream(is); int data = is.available(); byte[] byteArray2 = new byte[data]; // inst.read(byteArray2); String str = new String(byteArray2); System.out.println(“——-Data read from file———“); System.out.println(str); } catch (Exception exception) { System.out.println(exception); } } }
Kết quả:
——-Data da duoc ghi vao file——— Welcome to VietTuts.Vn! ——-Data read from file——— Welcome to VietTuts.Vn!
Bạn có thể sử dụng khối catch với câu lệnh try-with-resources giống như một câu lệnh try thông thường.
Java
|
Output:
File content copied to another one.
Resource are closed and message has been written into the gfgtextfile.txt
Feeling lost in the vast world of Backend Development? It’s time for a change! Join our Java Backend Development – Live Course and embark on an exciting journey to master backend development efficiently and on schedule. What We Offer:
- Comprehensive Course
- Expert Guidance for Efficient Learning
- Hands-on Experience with Real-world Projects
- Proven Track Record with 100,000+ Successful Geeks
Last Updated :
30 Nov, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment…
The Java Tutorials have been written for JDK 8. Examples and practices described in this page don’t take advantage of improvements introduced in later releases and might use technology no longer available.See Java Language Changes for a summary of updated language features in Java SE 9 and subsequent releases.See JDK Release Notes for information about new features, enhancements, and removed or deprecated options for all JDK releases.
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
FileReader
and
BufferedReader
to read data from the file.
FileReader
and
BufferedReader
are resources that must be closed after the program is finished with it:
static String readFirstLineFromFile(String path) throws IOException { try (FileReader fr = new FileReader(path); BufferedReader br = new BufferedReader(fr)) { return br.readLine(); } }
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 the interface
java.lang.AutoCloseable
. Because the
FileReader
and
BufferedReader
instances are declared in a
try
-with-resource statement, they will be closed regardless of whether the
try
statement completes normally or abruptly (as a result of the method
BufferedReader.readLine
throwing an
IOException
).
Prior to Java SE 7, you can use a
finally
block to ensure that a resource is closed regardless of whether the
try
statement completes normally or abruptly. The following example uses a
finally
block instead of a
try
-with-resources statement:
static String readFirstLineFromFileWithFinallyBlock(String path) throws IOException { FileReader fr = new FileReader(path); BufferedReader br = new BufferedReader(fr); try { return br.readLine(); } finally { br.close(); fr.close(); } }
However, this example might have a resource leak. A program has to do more than rely on the garbage collector (GC) to reclaim a resource’s memory when it’s finished with it. The program must also release the resoure back to the operating system, typically by calling the resource’s
close
method. However, if a program fails to do this before the GC reclaims the resource, then the information needed to release the resource is lost. The resource, which is still considered by the operaing system to be in use, has leaked.
In this example, if the
readLine
method throws an exception, and the statement
br.close()
in the
finally
block throws an exception, then the
FileReader
has leaked. Therefore, use a
try
-with-resources statement instead of a
finally
block to close your program’s resources.
If the methods
readLine
and
close
both throw exceptions, then the method
readFirstLineFromFileWithFinallyBlock
throws the exception thrown from the
finally
block; the exception thrown from the
try
block is suppressed. In contrast, in the example
readFirstLineFromFile
, if exceptions are thrown from both the
try
block and the
try
-with-resources statement, then the method
readFirstLineFromFile
throws the exception thrown from the
try
block; the exception thrown from the
try
-with-resources block is suppressed. In Java SE 7 and later, you can retrieve suppressed exceptions; see the section Suppressed Exceptions for more information.
The following example retrieves the names of the files packaged in the zip file
zipFileName
and creates a text file that contains the names of these files:
public static void writeToFileZipFileContents(String zipFileName, String outputFileName) throws java.io.IOException { java.nio.charset.Charset charset = java.nio.charset.StandardCharsets.US_ASCII; java.nio.file.Path outputFilePath = java.nio.file.Paths.get(outputFileName); // Open zip file and create output file with // try-with-resources statement try ( java.util.zip.ZipFile zf = new java.util.zip.ZipFile(zipFileName); java.io.BufferedWriter writer = java.nio.file.Files.newBufferedWriter(outputFilePath, charset) ) { // Enumerate each entry for (java.util.Enumeration entries = zf.entries(); entries.hasMoreElements();) { // Get the entry name and write it to the output file String newLine = System.getProperty(“line.separator”); String zipEntryName = ((java.util.zip.ZipEntry)entries.nextElement()).getName() + newLine; writer.write(zipEntryName, 0, zipEntryName.length()); } } }
In this example, the
try
-with-resources statement contains two declarations that are separated by a semicolon:
ZipFile
and
BufferedWriter
. When the block of code that directly follows it terminates, either normally or because of an exception, the
close
methods of the
BufferedWriter
and
ZipFile
objects are automatically called in this order. Note that the
close
methods of resources are called in the opposite order of their creation.
The following example uses a
try
-with-resources statement to automatically close a
java.sql.Statement
object:
public static void viewTable(Connection con) throws SQLException { String query = “select COF_NAME, SUP_ID, PRICE, SALES, TOTAL from COFFEES”; try (Statement stmt = con.createStatement()) { ResultSet rs = stmt.executeQuery(query); while (rs.next()) { String coffeeName = rs.getString(“COF_NAME”); int supplierID = rs.getInt(“SUP_ID”); float price = rs.getFloat(“PRICE”); int sales = rs.getInt(“SALES”); int total = rs.getInt(“TOTAL”); System.out.println(coffeeName + “, ” + supplierID + “, ” + price + “, ” + sales + “, ” + total); } } catch (SQLException e) { JDBCTutorialUtilities.printSQLException(e); } }
The resource
java.sql.Statement
used in this example is part of the JDBC 4.1 and later API.
Note: A
try
-with-resources statement can have
catch
and
finally
blocks just like an ordinary
try
statement. In a
try
-with-resources statement, any
catch
or
finally
block is run after the resources declared have been closed.
An exception can be thrown from the block of code associated with the
try
-with-resources statement. In the example
writeToFileZipFileContents
, an exception can be thrown from the
try
block, and up to two exceptions can be thrown from the
try
-with-resources statement when it tries to close the
ZipFile
and
BufferedWriter
objects. If an exception is thrown from the
try
block and one or more exceptions are thrown from the
try
-with-resources statement, then those exceptions thrown from the
try
-with-resources statement are suppressed, and the exception thrown by the block is the one that is thrown by the
writeToFileZipFileContents
method. You can retrieve these suppressed exceptions by calling the
Throwable.getSuppressed
method from the exception thrown by the
try
block.
See the Javadoc of the
AutoCloseable
and
Closeable
interfaces for a list of classes that implement either of these interfaces. The
Closeable
interface extends the
AutoCloseable
interface. The
close
method of the
Closeable
interface throws exceptions of type
IOException
while the
close
method of the
AutoCloseable
interface throws exceptions of type
Exception
. Consequently, subclasses of the
AutoCloseable
interface can override this behavior of the
close
method to throw specialized exceptions, such as
IOException
, or no exception at all.
Getty Images/iStockphoto
A simple ‘try with resources’ in Java example
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. Failure to close these resources after a developer opens a handle to them can cause memory leaks, trigger avoidable garbage collection routines and strain a server’s CPU.
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. This helps developers write more effective and bug-free code.
Ví dụ 1 – try-with-resources
Ví dụ sau ghi một chuỗi vào một file. Nó sử dụng một thể hiện của đối tượng FileOutputStream để ghi dữ liệu vào file. FileOutputStream là một tài nguyên phải được đóng lại sau khi chương trình kết thúc. Vì vậy, trong ví dụ này, việc đóng tài nguyên được thực hiện bằng chính nó.
package vn.viettuts; import java.io.FileOutputStream; public class TryWithResources1 { public static void main(String args[]) { // su dung try-with-resources try (FileOutputStream fos = new FileOutputStream(“/message1.txt”)) { String msg = “Welcome to VietTuts.Vn!”; // converting string thanh mang byte byte byteArray[] = msg.getBytes(); fos.write(byteArray); System.out.println(“Thong diep da duoc ghi vao file thanh cong!”); } catch (Exception exception) { System.out.println(exception); } } }
Kết quả:
Thong diep da duoc ghi vao file thanh cong!
TL;DR: How Do I Use the Try-with-Resources in Java?
The try-with-resources statement in Java is a feature that automatically closes resources used within the try block, used with the syntax
try (FileReader fr = new FileReader("file.txt")){}
. This is a powerful tool that can help you manage resources effectively and avoid common pitfalls associated with resource leaks.
Here’s a simple example:
try (FileReader fr = new FileReader("file.txt")) { // use the resource } // Output: // The FileReader will be closed automatically after the try block.
In this example, we create a new FileReader instance within the parentheses of the try statement. This FileReader instance is a resource that needs to be closed after use. By declaring the resource within the try block, Java automatically closes the FileReader after the try block is exited, whether by normal execution flow or by an exception being thrown.
This is just a basic way to use the try-with-resources statement in Java, but there’s much more to learn about managing resources effectively. Continue reading for more detailed explanations and advanced usage scenarios.
Table of Contents
- Unpacking Java’s Try-With-Resources
- Leveraging Try-With-Resources with Multiple Resources
- Handling Exceptions in Try-With-Resources
- Exploring Alternative Methods for Resource Management
- Troubleshooting Java’s Try-With-Resources
- Understanding Resource Management in Java
- Expanding Your Java Horizons: The Bigger Picture
- Wrapping Up:
Try-with-resources Java 9 Enhancement
Before Java 9 a resource that is to be automatically closed must be created inside the parentheses of the try block of a try-with-resources construct. From Java 9, this is no longer necessary. If the variable referencing the resource is effectively final, you can simply enter a reference to the variable inside the try block parentheses. Here is an example of the Java 9 try-with-resources enhancement:
private static void printFile() throws IOException { FileInputStream input = new FileInputStream(“file.txt”); try(input) { int data = input.read(); while(data != -1){ System.out.print((char) data); data = input.read(); } } }
Notice how the
input
variable is now declared and has a
FileInputStream
assigned
outside the try block. Notice also, how the
input
variable is references inside the parentheses
of the try block. This way, Java will still close it properly once the try block is exited.
try-with-resources With Multiple Resources
We can declare multiple resources just fine in a try-with-resources block by separating them with a semicolon:
try (Scanner scanner = new Scanner(new File("testRead.txt"));
PrintWriter writer = new PrintWriter(new File("testWrite.txt"))) {
while (scanner.hasNext()) {
writer.print(scanner.nextLine());
}
}
Wrapping Up:
In this comprehensive guide, we’ve delved into the nitty-gritty of Java’s try-with-resources statement, a powerful feature that simplifies resource management and ensures your applications run efficiently and reliably.
We began with the basics, understanding how the try-with-resources statement works and how to use it in simple scenarios. We then delved into more advanced usage, exploring how to use the try-with-resources statement with multiple resources and handle exceptions. We also tackled common challenges you might encounter when using the try-with-resources statement, such as dealing with non-auto-closeable resources and handling multiple exceptions.
Along the way, we examined alternative methods for managing resources in Java, such as using a
finally
block or the
close()
method. We compared these methods with the try-with-resources statement, highlighting the advantages and drawbacks of each approach.
Here’s a quick comparison of the methods we’ve discussed:
Method | Pros | Cons |
Try-With-Resources | Automatic resource management, robust exception handling | Only works with auto-closeable resources |
Finally Block | Works with all resources | More verbose, error-prone |
Close() Method | Straightforward, works with all resources | Manual, doesn’t handle exceptions automatically |
Whether you’re just starting out with Java or you’re looking to level up your resource management skills, we hope this guide has given you a deeper understanding of the try-with-resources statement and its capabilities.
With its automatic resource management and robust exception handling, the try-with-resources statement is a powerful tool for writing cleaner, more reliable Java code. Happy coding!
Java Try With Resources
- Try-with-resources Video
- Try-with-resources
- Try-with-resources Java 9 Enhancement
- Using Multiple Resources
- Custom AutoClosable Implementations
- Try-with-resources Exception Handling
- Resource Management With Try-Catch-Finally, Old School Style
Jakob Jenkov |
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. To do so, you must open and use the resource within a Java try-with-resources block. When the execution leaves the try-with-resources block, any resource opened within the try-with-resources block is automatically closed, regardless of whether any exceptions are thrown either from inside the try-with-resources block, or when attempting to close the resources.
This Java try-with-resources tutorial explains how the Java try-with-resources construct works, how to properly use it, and how exceptions are handled that are thrown both from inside the try-with-resources block, and during the closing of the resources.
Java
|