Does the catch in try-with-resources cover the cod

2020-07-18 02:58发布

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())?

3条回答
看我几分像从前
2楼-- · 2020-07-18 03:31

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楼-- · 2020-07-18 03:35

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.

查看更多
▲ chillily
4楼-- · 2020-07-18 03:37

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.

查看更多
登录 后发表回答