【问题标题】:Java, try-finally without catchJava,try-finally 没有捕获
【发布时间】:2017-01-29 23:28:49
【问题描述】:

我正在使用类生成器的这种方法:

public void executeAction(String s) throws MyException {
    if (s.equals("exception"))
        throw new MyException("Error, exception", this.getClass().getName());
}

public void close() {
      System.out.println("Closed");
}

我已将它们与这段代码一起使用:

public void execute() throws MyException  
    Generator generator = new Generator();
    try {
        String string = "exception";
        generator.executeAction(string);
    } finally {
        generator.close();
    }

}

在 main 我处理了异常:

try {
        manager.execute();
    } catch (MyException e) {
        System.err.println(e.toString());
    }
}

在 main 我可以抓住它。这是正常行为吗?

【问题讨论】:

  • 您为什么希望抑制该异常?
  • 抱歉,我更正了问题
  • 最终是否生效异常。所以如果一个异常被抛出并且没有被捕获不会影响finally

标签: java exception exception-handling try-catch-finally try-with-resources


【解决方案1】:

是的,这是正常行为。至少它确保生成器已关闭,但如果 finally 抛出异常,可能会抑制 try 块中的异常。

对于 java7,您应该使用 try-with-resources。

  1. Generator 实现AutoCloseable,它会执行你已经拥有的.close() 方法,所以除了实现之外没有真正的改变。

  2. 将执行方法更改为使用 try-with-resources

  try(Generator generator = new Generator()) {
      String string = "exception";
      generator.executeAction(string);
  }

除了更少的代码之外,好处是@Mouad 提到的抑制异常得到了正确处理。 .close() 调用的异常可从 e.getSuppressedException() 获得

【讨论】:

    【解决方案2】:

    例如,当您的 Generator.close() 方法抛出另一个异常 -in finally 块时,您将得到一个抑制的异常:

    public void close() {
      throw new OtherException("some msg");//This Exception will be added to your main Exception (MyException) as a Suppressed Exception 
      System.out.println("Closed");
    }
    

    所以是的,这是正常行为。

    【讨论】:

      【解决方案3】:

      是的,这是正确的行为。从 try-with-resources 语句中抛出了抑制的异常,这不是你的情况。看看What is a suppressed exception?

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-06-01
        • 2016-07-20
        • 1970-01-01
        • 2011-02-13
        • 1970-01-01
        • 2010-11-23
        • 1970-01-01
        • 2011-10-31
        相关资源
        最近更新 更多