40

In Java 7's try-with-resources, I don't know which order the finally block and the auto-closing happens. What's the order?

BaseResource b = new BaseResource(); // not auto-closeable; must be stop'ed
try(AdvancedResource a = new AdvancedResource(b)) {

}
finally {
    b.stop(); // will this happen before or after a.close()?
}
Nathan
  • 8,093
  • 8
  • 50
  • 76
djechlin
  • 59,258
  • 35
  • 162
  • 290

2 Answers2

61

The resource gets closed before catch or finally blocks. See this tutorial.

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.

To evaluate this is a sample code:

class ClosableDummy implements Closeable {
    public void close() {
        System.out.println("closing");
    }
}

public class ClosableDemo {
    public static void main(String[] args) {
        try (ClosableDummy closableDummy = new ClosableDummy()) {
            System.out.println("try exit");
            throw new Exception();
        } catch (Exception ex) {
            System.out.println("catch");
        } finally {
            System.out.println("finally");
        }


    }
}

Output:

try exit
closing
catch
finally
Nathan
  • 8,093
  • 8
  • 50
  • 76
jmj
  • 237,923
  • 42
  • 401
  • 438
  • 4
    Crazy. So Try-with-resources is no good replacement for try-catch-finally when the resource is needed to handle the catch. – Gustavo Jun 27 '17 at 15:44
  • 1
    Resources don't needs handling in `catch` block. – jmj Jun 27 '17 at 17:15
  • 2
    The catch block may need the resource to complete it's task. – Gustavo Jun 27 '17 at 17:36
  • This is bad. I thought I could call `rollback()` in `finally` while using try-with-resources on an SQL connection. This way, I can't. See also https://stackoverflow.com/a/218495/593146 – Zyl Jun 16 '21 at 08:31
1

According to the JLS 13; 14.20.3.2. Extended try-with-resources

The finally block is the last to be executed:

Furthermore, all resources will have been closed (or attempted to be closed) by the time the finally block is executed, in keeping with the intent of the finally keyword.

Roland
  • 7,525
  • 13
  • 61
  • 124