5

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

 2 years ago
source link: https://jack-zheng.github.io/hexo/2021/12/02/Java-try-with-resources/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

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

发表于

2021-12-02 更新于 2022-03-02 分类于 java

阅读次数: 1 本文字数: 590 阅读时长 ≈ 1 分钟

Refer: StackOverflow

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

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

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK