English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this tutorial, we will learn try-with-The resources statement closes resources automatically.
try-with-The resources statement automatically closes all resources at the end of the statement. Resources are objects that need to be closed when the program ends.
Its syntax is:
try (resource declaration) { // use of the resource } catch (ExceptionType e1) { // catch block }
From the above syntax, we can see that we declare try-with-resources statement:
Declare and instantiate resources within the try clause.
Specify and handle all exceptions that may be raised when closing resources.
Note:try-with-The resources statement closes all resources that implement the AutoCloseable interface.
Let's implement try-with-For example, let's take the resources statement for an example.
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, the instance BufferedReader we use reads data from the test.txt file.
In try-with-Declaring and instantiating BufferedReader in the resources statement ensures that its instance can be closed, regardless of whether the try statement completes normally or an exception is thrown.
If an exception occurs, you can use the exception handling block orthrows keywordto handle them.
In the above example, you can retrieve suppressed exceptions from try-with-Resources statement throws an exception:
test.txt file not found.
Close the BufferedReader object.
can also throw exceptions from the try block because file reading may fail at any time for various reasons.
If from try block and try-with-If all resources statements throw exceptions, the exception in the try block will be thrown, and the try-with-from the exceptions in the resources statement.
In Java 7and higher versions, you can retrieve suppressed exceptions by calling the method Throwable.getSuppressed() from exceptions thrown in the try block.
This method returns an array of all suppressed exceptions. We got 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.length; i++) { System.out.println("Suppressed exception=>" + suppressedExceptions[i]); } }
This is using try-with-Advantages of resources:
In Java 7Before introducing this feature, we must use the finally block to ensure that resources are closed to avoid resource leaks.
This is similar toExample1of the programHowever, in this program, we use the finally block to close resources.
import java.io;*; class Main { public static void main(String[] args) { BufferedReader br = null; String line; try { System.out.println("Enter 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("Enter the finally block"); try { if (br != null) { br.close(); } } catch (IOException e) { System.out.println("IOException in finally block => ");+e.getMessage()); } } } }
Output result
Enter the try block Line => line from test.txt file Enter the finally block
From the above example, it can be seen that using a finally block to clean up resources makes the code more complex.
Did you notice the try ... catch block in the finally block? This is because an IOException may also occur when closing the BufferedReader instance within this finally block, so it is also caught and handled.
try-with-Execution of resources statementAutomatic resource management.We do not need to explicitly close resources because the JVM will automatically close them. This makes the code more readable and easier to write.
We can try-with-Resources are separated by semicolons to declare multiple resources in a statement;
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 no exceptions are generated when the program is executed, the Scanner object reads a line from the testRead.txt file and writes it to the new testWrite.txt file.
Multiple declarations, try-with-The resources statement closes these resources in the opposite order. In this example, the PrintWriter object is closed first, followed by the Scanner object.
In Java 7In, the try-with-The resources statement has a limitation. The resource must be declared locally within its block.
try (Scanner scanner = new Scanner(new File("testRead.txt"))) { // code }
If we try in Java 7If resources are declared outside the block, an error message will be thrown.
Scanner scanner = new Scanner(new File("testRead.txt")); try (scanner) { // code }
To resolve this error, Java 9 Improved the try-with-The resources statement, so that resources can be used even if they are not declared locally, will now execute without throwing any compilation errors.