【问题标题】:Exception in try with resources clausetry with resources 子句中的异常
【发布时间】:2015-06-21 19:37:48
【问题描述】:
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中的代码如代码所述执行成功,而try with resource clause中出现了一些exception,则说明文件的auto closing出现异常。

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

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

我可以捕获那个异常,以便剩余的程序也可以执行吗?

【问题讨论】:

  • 你为什么不自己尝试一下?
  • 一个finally 子句在这里工作
  • @Turing85 :我不知道如何让try with resources clause 抛出异常。
  • 是的,异常会被抛出到JVM,如果你不捕捉它会终止我的程序
  • @ValentinRuano :我也猜到了,但有没有其他解决方案。因为try block后面的代码可能很大,所以把整个代码放在finally block里面是不划算的。

标签: java ioexception try-with-resources


【解决方案1】:

如果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) {
     // ...
}

【讨论】:

  • 你不需要外层try
  • @Turing85 谢谢你,我已经修正了我的答案。
【解决方案2】:

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

【讨论】:

    【解决方案3】:

    我认为程序的其余部分最终会运行,请尝试并报告。

    课堂演示

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

    【讨论】:

    • 是的,它有效。我已经猜到了这个想法。但是,如果try block 之后的代码很大,那么在finally block 中放置一个巨大的代码是不值得的。
    • 你应该小心finally-blocks。 finally 总是被执行,which can lead to funny behavioursfinally 应该用于一些清理工作,这需要完成并且将其用于其他目的可能会导致不需要的结果。
    • @kevingomes 您可以随时将代码提取到自己的方法中。
    • @Turing85,我必须部分同意你的观点,在一个更复杂的例子中,为了对问题进行更具体的处理,建议使用特定的 catch,对于当前的例子,我认为 finally不过就够了。不理解“有趣的行为”中的“有趣”部分,finally 的行为是相当健壮的,即使它可能不适合这种情况。你能详细说明一下吗?
    • @ValentinRuano look at thisthis
    【解决方案4】:

    只需删除文件 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");
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-02
      • 1970-01-01
      • 2021-07-27
      • 1970-01-01
      • 2014-05-21
      • 1970-01-01
      • 1970-01-01
      • 2013-07-18
      相关资源
      最近更新 更多