Those examples of using Java resources can be written as an example that you specify where r initially set to null , but if they used Java 7 try-with-resources (Assuming Resource implements AutoCloseable ):
try (Resource r = openResource()) {
Then they will be equivalent to the first example, where openResource() is called before the try block. The Java language specification for the try-with-resources defines semantics as equivalent to assigning a variable with an initializer before the block, and then entering into try-catch-finally .
There is a problem with the exception that occurred before the try block was entered. The problem is mostly theoretical. If openResource() returns normally, and there are no intermediate statements between assigning r and the start of the try block, it is unlikely, although not impossible, that some other thread will gain control before the try block begins, but even when your thread started again, it will enter the try block without incident. If another thread did something that caused the JVM to shut down, such as calling System.exit , you usually don't need to worry about closing resources. And even this case is unlikely.
If, on the other hand, there was a problem opening the resource, presumably openResource() will openResource() , which will prevent the assignment of r .
source share