JDK7 new features: Try- with-resources
try-with-resources is a new exception handling mechanism introduced in JDK 7, which is mainly used for automatic resource management, and can easily shut down resources used in a try-catch statement block. It ensures that resources are properly closed when they are no longer needed. This mechanism simplifies resource management and makes the release of resources safer and more predictable.
resource: are objects that must be closed when the program completes (e.g., the file resource File, IO streams, Sockets, ServerSocket network objects, database link objects, etc.). try-with-resources statement ensures that each resource is closed at the end of the statement.
General Switching Resource Methods
class Myresources1 implements AutoCloseable {
@Override
public void close() throws Exception {
("resource (such as manpower or tourism)1Close method execution");
throw new Exception("resource (such as manpower or tourism)1Closing anomaly");
}
}
class Myresources2 implements AutoCloseable {
@Override
public void close() throws Exception {
("resource (such as manpower or tourism)2Close method execution");
throw new Exception("resource (such as manpower or tourism)2Closing anomaly");
}
}
To avoid exceptions during code execution, use thetry-catch-finally
Perform exception catching
Myresources1 myresources1 =null;
Myresources2 myresources2 = null;
try{
myresources1 = new Myresources1();
myresources2 = new Myresources2();
("hello");
}catch (Exception e){
();
}finally {
if (myresources1!=null){
try {
();
}catch (Exception e){
();
}finally {
if (myresources2!=null){
try {
();
}catch (Exception e){
();
}
}
}
}
}
Try- with-resources controls the resource syntax:
try(Myresources1 myresources1 = new Myresources1();
Myresources2 myresources2 = new Myresources2();){
("hello");
//int a = 2/0;
}catch (Exception e){
();
}
Handling rules
- Whenever a class that implements the AutoCloseable or Closeable interface declares an instance of that class in try(), the close method is called at the end of the try. Regardless of whether an exception is thrown (int i=1/0 throws an exception), the instance in try() will have the close method called.
![imag
](/yuque/0/2024/png/42425790/#averageHue=%231f2125&clientId=ua8faed9b-5ab9-4&from=paste&height=259&id=TKIhf&originHeight=259&originWidth=735&originalType=binary&ratio=1&rotation=0&showTitle=false&size=37054&status=done&style=none&taskId=u35bf969c-e938-4d98-ab98-4df1f077383&title=&width=735)
- The later an object is declared, the sooner it will be closed.
- The close method is automatically called at the end of try, and this action precedes the method called in finally.
Anomaly suppression issues
Myresources1 myresources1 = null;
try{
myresources1 = new Myresources1();
//arithmetic anomaly (math.)
(10/0);
}finally {
if (myresources1!=null)
();
}
//myresources1resemble
class Myresources1 implements AutoCloseable {
@Override
public void close() throws Exception {
("resource (such as manpower or tourism)1Close method execution");
throw new Exception("resource (such as manpower or tourism)1Closing anomaly");
}
}
Run an exception print:
At this point you can see that the exception only printsclose()
method, and the 10/0 exception is suppressed for the
try(Myresources1 myresources1 = new Myresources1();){
(10/0);
}
Run an exception print:<br When an exception is thrown, there may be other exceptions that are suppressed because of the exception and thus cannot be thrown properly. This can be accomplished with theaddSuppressed()
method logs these suppressed methods, and the suppressed exception then appears in the stack information of the thrown exception, which can be accessed via thegetSuppressed()
method to get these exceptions. This has the advantage of not losing any exceptions and makes it easier for us to debug.
Decompile the code:
Myresources1 myresources1 = new Myresources1();
Throwable var2 = null;
try {
(10 / 0); } catch (Throwable var11) {
} catch (Throwable var11) {
var2 = var11; throw var11; } catch (Throwable var11) { var2 = var11
throw var11; } catch (Throwable var11) { var2 = var11; throw var11; }
} finally {
if (myresources1 ! = null) {
// Determine if the program is running with an exception
if (var2 ! = null) { //There is an exception.
try {
();
} catch (Throwable var10) {
(var10); //add the exception thrown by close() as a suppressed exception
}
} else { // program runs with no exceptions
();
}
}
}
Cyclic Print Suppression Exception
try(Myresources1 myresources1 = new Myresources1();){
(10/0);
}catch (Exception e){
();
Throwable[] suppressed = ();
for (Throwable t : suppressed){
();
}
}
Run results:
Usage Scenarios
try-with-resources
syntax is suitable for any scenario where you need to automatically manage resource closures to prevent resource leaks.
Simple and crude point is that, ctrl point in to see the current resource, as long as the current resource implements the AutoCloseable or Closeable interface can be used. However, the specific use of the business scenarios to be realized according to the decision.
Scenes that don't fit:
- The resource does not implement the AutoCloseable or Closeable interfaces:
If the resource does not realizeAutoCloseable
maybeCloseable
interface, then it cannot be used in thetry-with-resources
is automatically closed in the statement. In this case, it is still necessary to close the resource manually or use some other mechanism to ensure that the resource is closed correctly.
- Resources need to be used outside the try block:
try-with-resources
The resources in the statement are automatically closed after the try block is executed, so they are not accessible outside the try block. If a resource needs to be in thetry
block is used externally, then it is not possible to use thetry-with-resources
statements to manage these resources.
- The timing of resource closure needs to be finely controlled:
In some cases, a developer may need to decide when to close a resource based on specific logic or conditions, rather than on thetry
Close immediately at the end of the block.try-with-resources
statements do not provide this kind of fine-grained control and therefore may not be applicable in these scenarios.
- Resource closures may throw exceptions and require special handling:
even thoughtry-with-resources
statement will attempt to shut down the resource and catch exceptions thrown during the shutdown process, but these exceptions are usually suppressed rather than thrown directly. If the developer needs to specifically handle these shutdown exceptions, or needs to associate them with thetry
block to distinguish between other exceptions thrown in the block, then thetry-with-resources
May not be the best option.
- Resources need to be shared across multiple try blocks:
If a resource needs to be used in more than onetry
block is shared and used, then using thetry-with-resources
statements may become complex or infeasible. Because eachtry-with-resources
statements all try to close their declared resources at the end, which may result in the resource already being closed when it is needed.
- Resource closure logic is complex:
If the shutdown logic for a resource is very complex, or if you need to perform some specific action before shutting it down (e.g., rolling back a transaction, releasing a lock, etc.), then use thetry-with-resources
statements may not be sufficient. In these cases it may be necessary to write more complexfinally
block to ensure that the resource is closed correctly. In summary, thetry-with-resources
statement, while a powerful resource management mechanism, is not applicable to all scenarios. When choosing whether to use thetry-with-resources
When doing so, developers need to make decisions based on the specific needs and characteristics of the resource.
Pros:
- Simplified resource management code: no need to explicitly add the
finally
Writing the code for resource closure in a block reduces the amount of code and the possibility of errors. - Improve code readability: make the management of resources clearer and more intuitive, allowing developers to focus more on business logic.
- Ensure that resources are shut down in a timely manner: even when
try
An exception occurs in the block, and the resource is also automatically closed, avoiding the risk of resource leakage. - Multiple resource support: multiple resources can be managed at the same time and they will all be closed correctly in the reverse order of their declaration.
Drawbacks:
-
The types of resources supported are limited: not all classes can be used as
try-with-resources
resources that can only be realized if theAutoCloseable
maybeCloseable
interface for the class to work. -
Performance Considerations:
even though
try-with-resources
In most cases the performance impact is negligible, but in extreme cases (e.g., frequent opening and closing of a large number of resources in a performance-sensitive application), it may introduce some additional overhead. This is becausetry-with-resources
statement generates additional code at compile time to manage resource closure. -
misidentification
try()
Objects declared in the
FileWriter fw = new FileWriter("");
fw = new FileWriter("e:/");
try(FileWriter fw = new FileWriter("")){
fw = new FileWriter(""); //report an error
}catch (Exception e){
();
}
//At this point there will be a compilation error:The resource is1 of a try-with-resources statement cannot be assigned
Official Documentation:
It is a compile-time error if final appears more than once as a modifier for each variable declared in a resource specification.
A variable declared in a resource specification is implicitly declared final (§4.12.4) if it is not explicitly declared final.
Every variable declared in a resource specification that has final as a modifier more than once is a compile-time error.
A variable declared in a resource specification that is not explicitly declared final is implicitly declared final (§4.12.4).
Variables declared in try-with-resource are implicitly marked with the final keyword, so they can no longer be assigned.
Summary:
try-with-resources
The advantages of try-with-resources usually outweigh the disadvantages, and in most cases it is a safer, cleaner, and more reliable way to manage resources. Depending on the business scenario, you may want to use try-with-resources instead of try-catch-finally, which produces cleaner, clearer code and more reliable exception messages.