Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

The Operation method of realizing try-with-resources exception Management Mechanism with Java try () statement

2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

Java try () statement implements the operation method of try-with-resources exception management mechanism. In view of this problem, this article introduces the corresponding analysis and solution in detail, hoping to help more partners who want to solve this problem to find a more simple and feasible method.

Java try () statement implements try-with-resources exception management mechanism

The new feature of java7 is that resources used in try statement blocks no longer need to be manually closed, but will be automatically closed after the end of the statement block, similar to the use of with..as in python.

To take advantage of this feature, you need to implement the AutoCloseable interface, and there is only one close method to close the resource.

Public interface AutoCloseable {public void close () throws Exception;}

All streams, which implement this interface, can be instantiated in try (). Custom classes can also use this feature as long as they implement this interface.

When not using try-with-resources, the resources used will be released in finally package stream; import java.io.File;import java.io.FileInputStream;import java.io.IOException; public class TestStream {public static void main (String [] args) {File f = new File ("d:/test.txt"); FileInputStream fis = null; try {fis = new FileInputStream (f) } catch (IOException e) {e.printStackTrace ();} finally {/ / close the stream if (null! = fis) try {fis.close () in finally } catch (IOException e) {/ / TODO Auto-generated catch block e.printStackTrace ();}} when using try-with-resources

The form is try (), and multiple statements can be contained in parentheses.

Package stream; import java.io.File;import java.io.FileInputStream;import java.io.IOException; public class TestStream {public static void main (String [] args) {File f = new File ("d:/lol.txt") / / define the flow in try (). When try,catch or finally ends, try (FileInputStream fis = new FileInputStream (f)) {byte [] all = new byte [(int) f.length ()]; fis.read (all); for (byte b: all) {System.out.println (b) }} catch (IOException e) {e.printStackTrace ();} Custom AutoCloseable implementation

Print information in the close method of TestAutoCloseable

Package test; public class TestAutoCloseable implements AutoCloseable {public TestAutoCloseable () {System.out.println ("class TestAutoCloceable");} public void close () {System.out.println ("function close () executed");}}

Test code

Package test; public class TestFeature {public static void main (String [] args) {/ / TODO Auto-generated method stub try (TestAutoCloseable testAutoCloseable = new TestAutoCloseable ()) {}

As a result, the close method is called

The try-with-resources statement gracefully closes resources

During Java programming, if external resources (files, database connections, network connections, etc.) are opened, we must manually close them after they have been used.

Because external resources are not managed by JVM, we cannot enjoy JVM's garbage collection mechanism. if we do not ensure that external resources are closed at the right time when programming, it will lead to external resource leakage, followed by many serious problems, such as abnormal occupation of files, excessive database connections, connection pool overflow, and so on.

Before java1.7, we closed resources in the following way: public class CloseTest {public static void main (String [] args) {FileInputStream fileInputStream = null; try {fileInputStream = new FileInputStream ("file.txt"); fileInputStream.read ();} catch (IOException e) {e.printStackTrace () } finally {if (fileInputStream! = null) {try {fileInputStream.close ();} catch (IOException e) {e.printStackTrace ();}

To ensure that external resources must be closed, the closing code is usually written into the finally code block, with exceptions that may be thrown when the resource is closed, and the classic code is born.

However, after the java1.7 version, a new syntax candy has been added, which is the try-with-resources statement.

Let's start with a demo to make it easier to understand public class CloseTest {public static void main (String [] args) {try (FileInputStream fileInputStream1 = new FileInputStream ("file1.txt"); FileInputStream fileInputStream2 = new FileInputStream ("file2.txt")) {fileInputStream1.read (); fileInputStream2.read ();} catch (IOException e) {e.printStackTrace ();}

Place the creation of the handle object of the external resource in parentheses after the try keyword, and when the try-catch code block is executed, Java ensures that the close method of the external resource is called. Multiple statements are broken with semicolons.

After decompilation, we can see public static void main (String [] args) {try {FileInputStream inputStream = new FileInputStream (new File ("test")); Throwable var2 = null; try {System.out.println (inputStream.read ());} catch (Throwable var12) {var2 = var12; throw var12 } finally {if (inputStream! = null) {if (var2! = null) {try {inputStream.close ();} catch (Throwable var11) {var2.addSuppressed (var11);}} else {inputStream.close () } catch (IOException var14) {throw new RuntimeException (var14.getMessage (), var14);}}

Through decompiled code, you may notice that there is a special handling of exceptions in the code:

Var2.addSuppressed (var11)

This is another knowledge point involved in try-with-resource grammar, called exception suppression. When dealing with external resources (such as reading or writing), if you encounter an exception, and in the subsequent process of closing the external resource, you will catch the exception encountered while handling the external resource, and the exception encountered when closing the resource will be "suppressed" but not discarded. The suppressed exception can be extracted through the getSuppressed method of the exception.

In the source code, there are explanations / * * Returns an array containing all of the exceptions that were * suppressed, typically by the {@ code try}-with-resources * statement, in order to deliver this exception. * * If no exceptions were suppressed or {@ linkplain * # Throwable (String, Throwable, boolean, boolean) suppression is * disabled}, an empty array is returned. This method is * thread-safe. Writes to the returned array do not affect future * calls to this method. * * @ return an array containing all of the exceptions that were * suppressed to deliver this exception. * @ since 1.7 * / public final synchronized Throwable [] getSuppressed () {if (suppressedExceptions = = SUPPRESSED_SENTINEL | | suppressedExceptions = = null) return EMPTY_THROWABLE_ARRAY; else return suppressedExceptions.toArray (EMPTY_THROWABLE_ARRAY);}

Because resources must be closed in any case (exception or non-exception), close () should be placed in the finally block before jdk1.6 to ensure the correct release of resources. If you use a version above jdk1.7, it is recommended that you use the try-with-resources statement.

This is the answer to the question about the operation method of the Java try () statement to implement the try-with-resources exception management mechanism. I hope the above content can be of some help to you. If you still have a lot of doubts to be solved, you can follow the industry information channel for more related knowledge.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report