Correct Idiom for Managing Multiple Chained Resources in Try-With-Resources Block

How to call a method in try with resources

This is from the documentation:

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.

https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html#:~:text=Note%3A%20A%20try%20%2Dwith%2D,resources%20declared%20have%20been%20closed.

Search for more elegant way to handle many nested try with resources

Why not to put all resources to the same try?

Here is simplified example:

try (MDC.MDCCloseable test= MDC.putCloseable("test", test);
MDC.MDCCloseable paw= MDC.putCloseable("paw", test.getPaw().toString()) {
/// etc, etc.
}

Exceptions from both try block and try-with-resources

How can an exception be thrown from both the try-with-resources statement and the try block ? If the exception is thrown from the try-with-resources statement, it means that resource initialization failed.

The try-with-resources statement not only initializes but also closes the resource, and closing may throw an exception.

This sentence comes right after a description of a similar situation when using try-finally, and compares it with try-with-resources.

Use resource in try with resource statement that was created before

You don't have to create the object in the try-with-resources statement, you just have to declare some local variables of a type that implements AutoCloseable. The variables are effectively final, and scoped to the try block, which allows the compiler to use them to generate the close boilerplate needed for cleanup.

FileInputStream f1 = new FileInputStream("test1.xml");
FileInputStream f2 = new FileInputStream("test2.xml");
// Don't need to create the resources here, just need to declare some vars
try (InputStream in1 = f1; InputStream in2 = f2) {
// error; in1 is final
in1 = new FileInputStream("t");
}

Better Resource Management with Java SE 7: Beyond Syntactic Sugar.

Addendum: Since java 9 the requirements have been relaxed; you don't have to redeclare the variables in the try block if the originals are effectively final.

JEP 213



Related Topics



Leave a reply



Submit