try with resources子句中的异常

kev*_*mes 2 java ioexception try-with-resources

class Demo
{
    public static void main(String args[]) throws java.io.IOException
    {
        try(FileInputStream fin = new FileInputStream("Demo.txt"))
        {
            //This block is executed successfully
        }

        System.out.println("Will it be executed if error occurs in try clause");
    }
}
Run Code Online (Sandbox Code Playgroud)

假设代码中的代码try block执行成功,有些代码exception发生try with resource clause,这意味着auto closing文件中发生了异常.

将如何处理该异常try with resource clause

我想问的是,该异常会被抛到JVM并且会突然终止我的程序并且该println语句不会被执行吗?

我可以捕获该异常,以便还可以执行剩余的程序吗?

K E*_*son 6

如果某个close方法AutoClosable抛出异常,try则在执行该块之后确实会抛出该异常.

如果需要处理异常,只需在try子句中添加一个catch子句即可.

以下代码说明了该行为:

public class Foo {

    public static class Bar implements AutoCloseable {

        @Override
        public void close() {
            throw new RuntimeException();
        }

    }

    public static void main(String args[]) {
        try (Bar b = new Bar()) {
            // This block is executed successfully
        }

        System.out.println("Will it be executed if error occurs in try clause");
    }
}
Run Code Online (Sandbox Code Playgroud)

它使用堆栈跟踪终止JVM:

Exception in thread "main" java.lang.RuntimeException
at test3.Foo$Bar.close(Foo.java:14)
at test3.Foo.main(Foo.java:25)
Run Code Online (Sandbox Code Playgroud)

25是}my try子句的结束行.

可以使用以下方法处理:

try (Bar b = new Bar()) {
    // This block is executed successfully
} catch (Exception e) {
     // ...
}
Run Code Online (Sandbox Code Playgroud)