Java 语法糖 - try with resource
Java About 961 words前提
需要实现AutoCloseable
接口。
示例一
Java 代码
public class Test8 {
public static void main(String[] args) {
try (InputStream is = new FileInputStream("/a.txt")) {
System.out.println(is);
} catch (IOException e) {
e.printStackTrace();
}
}
}
反编译 class
可以看到:
如果出现异常后在catch
中再次进行try
来关闭流,如关闭流出现异常就追加到异常中,最后抛出异常。
如果没有异常则正常close
。
public class Test8 {
public Test8() {
}
public static void main(String[] args) {
try {
FileInputStream is = new FileInputStream("/a.txt");
try {
System.out.println(is);
} catch (Throwable var5) {
try {
is.close();
} catch (Throwable var4) {
var5.addSuppressed(var4);
}
throw var5;
}
is.close();
} catch (IOException var6) {
var6.printStackTrace();
}
}
}
Views: 1,429 · Posted: 2022-04-26
————        END        ————
Give me a Star, Thanks:)
https://github.com/fendoudebb/LiteNote扫描下方二维码关注公众号和小程序↓↓↓
Loading...