Does the catch in try-with-resources cover the code in parentheses?

不羁岁月 提交于 2020-06-25 04:08:44

问题


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());
    }

Would my catch be invoked if an IOException is thrown inside getSomeStream()?

Or does the catch only cover the block inside curly braces, i.e. System.out.println(in.read())?


回答1:


From the JLS, your example is an extended 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.

In that case :

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.

So yes, the exception will be caught by your catch block.




回答2:


Yes, it is covered. Running

try (InputStream in = getSomeStream()) {
  System.out.println(in.read());
} catch (IOException e) {
  System.err.println("IOException: " + e.getMessage());
}

with

static InputStream getSomeStream() throws IOException {
  throw new IOException();
}

prints

IOException: null

So yes, the Exception thrown in the initialization part is caught in the catch block.




回答3:


The Oracle tutorials are authoritative but not normative. The JLS http://docs.oracle.com/javase/specs/jls/se8/html/jls-14.html#jls-14.20.3.2 answers your question completely: Yes.

Read the Fine Manual.



来源:https://stackoverflow.com/questions/43522560/does-the-catch-in-try-with-resources-cover-the-code-in-parentheses

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!