try with resources 子句中的异常

Exception in try with resources clause

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

假设try block中的代码执行成功,如代码中所述,exception中出现try with resource clause,即异常发生在auto closing中文件。

如何处理 try with resource clause 中的异常?

我想问的是,那个异常会不会抛给JVM,会突然终止我的程序,println语句不会被执行?

我能否捕获该异常,以便也可以执行剩余的程序?

如果 AutoClosableclose 方法抛出异常,它确实会在 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");
    }
}

它使用堆栈跟踪终止 JVM:

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

25 是我的 try 子句的结尾 } 所在的行。

可以通过以下方式处理:

try (Bar b = new Bar()) {
    // This block is executed successfully
} catch (Exception e) {
     // ...
}

我认为最终剩下的程序将是 运行,请尝试并报告。

class 演示

{
    public static void main(String args[]) throws java.io.IOException
    {
        try(FileInputStream fin = new FileInputStream("Demo.txt"))
        {
            //This block is executed successfully
        } finally {
           System.out.println("Will it be executed if error occurs in try clause");
        }
    }
}

只加catch子句,捕捉异常否则程序会终止

public static void main(String[] args) throws FileNotFoundException, IOException {
        try(FileInputStream fin = new FileInputStream("Demo.txt"))
        {
            //This block is executed successfully
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
        System.out.println("Will it be executed if error occurs in try clause");
    }

只需删除文件Demo.txt和运行下面的代码。

抛出此类异常的最简单方法是 运行 此代码,没有现有资源(在本例中为 Demo.txt):

public static void main(String args[])
    {
        try(FileInputStream fin = new FileInputStream("Demo.txt"))
        {

        } catch(IOException exc) {
            System.out.println("An exception has occured. Possibly, the file does not exist. " + exc);
        }

        System.out.println("Will it be executed if error occurs in try clause");
    }