0%

try-catch-with-resources 语法中各分支的执行顺序

Refer: StackOverflow

结论:先执行 try 中内容,再执行关闭资源的行为,然后是 catch 最后再 finally

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class CloseableDummy implements Closeable {
public void close() {
System.out.println("closing");
}
}

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

// try exit
// closing
// catch
// finally