Java,try-finally没有catch

时间:2017-01-29 23:28:50

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

我正在使用类Generator的这种方法:

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

}

主要处理了异常:

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

在主要我能抓住它。这是正常行为吗?

3 个答案:

答案 0 :(得分:1)

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

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

  1. Generator实施AutoCloseable,它会强制执行您已有的.close()方法,因此除了工具之外没有真正的变化。

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

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

    除了更少的代码之外,好处是@Mouad提到的被抑制的异常被正确处理。 .close()

    提供了e.getSuppressedException()来电的例外情况

答案 1 :(得分:0)

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

答案 2 :(得分:0)

例如,当您的Generator.close()方法抛出另一个异常时,您将获得一个被抑制的异常 - 最终阻止 - :

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

是的,这是一种正常行为。