Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
141 views
in Technique[技术] by (71.8m points)

java - Are resources closed before or after the finally?

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()?
}
question from:https://stackoverflow.com/questions/24129088/are-resources-closed-before-or-after-the-finally

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...