try-with-resources中的内容是否包含括号中的代码? [英] Does the catch in try-with-resources cover the code in parentheses?
问题描述
从文档不清楚,如果<try-with-resources
之后的c0>是否涵盖初始化部分.
It is unclear from the documentation if a catch
following a try-with-resources
covers the initialization part or not.
换句话说,给出以下代码片段:
In other words, given this code fragment:
try (InputStream in = getSomeStream()) {
System.out.println(in.read());
} catch (IOException e) {
System.err.println("IOException: " + e.getMessage());
}
如果在getSomeStream()
内部抛出IOException
,会调用我的catch
吗?
Would my catch
be invoked if an IOException
is thrown inside getSomeStream()
?
还是catch
仅覆盖大括号内的块,即System.out.println(in.read())
?
Or does the catch
only cover the block inside curly braces, i.e. System.out.println(in.read())
?
推荐答案
From the JLS, your example is an extended try-with-resources.
try-with-resources语句,至少包含一个catch子句和/或 finally子句称为扩展的try-with-resources语句.
A try-with-resources statement with at least one catch clause and/or a finally clause is called an extended try-with-resources statement.
在这种情况下:
翻译的效果是放入资源说明 在try语句内部". 这允许扩展的catch子句 try-with-resources语句捕获由于而导致的异常 自动初始化或关闭任何资源.
The effect of the translation is to put the resource specification "inside" the try statement. This allows a catch clause of an extended try-with-resources statement to catch an exception due to the automatic initialization or closing of any resource.
是的,您的catch
块将捕获该异常.
So yes, the exception will be caught by your catch
block.
这篇关于try-with-resources中的内容是否包含括号中的代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!