【问题标题】:What happens when with try resource when opening the resource throws exception?当打开资源时尝试资源抛出异常时会发生什么?
【发布时间】:2016-10-26 18:44:56
【问题描述】:
【问题讨论】:
标签:
java
exception
try-catch
【解决方案1】:
假设创建语句引发了错误,现在会发生什么?是吗
压制?
不,它不会被抑制,它会按原样抛出,实际上您的代码根据 Java 规范 的§14.20.3.1 相当于:
Throwable primaryExc = null;
Statement stmt = null;
try {
stmt = con.createStatement();
// use stmt here
} catch (Throwable e) {
primaryExc = e;
throw e;
} finally {
if (stmt != null) {
if (primaryExc != null) {
try {
stmt.close();
} catch (Throwable ex) {
primaryExc.addSuppressed(ex);
}
} else {
stmt.close();
}
}
}
所以你可以看到createStatement() 是否抛出异常,如果没有显式捕获,调用代码将不得不将此异常作为正常异常处理。
还请注意,就像上面的等效代码 sn-p 一样,如果 stmt.close() 在被 try-with-resources 语句自动调用时抛出异常,调用代码将不得不处理此异常,因为它不会也被压制了。
为try-with-resources 语句添加了抑制异常的功能,以便在try 块中已经引发异常时,能够获取在资源上调用close() 时引发的异常,例如示例:
try (Statement stmt = con.createStatement()) {
throw new RuntimeException("foo");
} catch (Exception e) {
// Here e is my RuntimeException, if stmt.close() failed
// I can get the related exception from e.getSuppressed()
}