繁体   English   中英

Java,try-finally 没有 catch

[英]Java, try-finally without catch

我正在使用类 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());
    }
}

主要是我可以抓住它。 这是正常行为吗?

是的,这是正常行为。 至少它确保生成器已关闭,但如果 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()

是的,这是正确的行为。 被抑制的异常是从 try-with-resources 语句中抛出的,这不是你的情况。 看看什么是抑制异常?

例如,当您的 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");
}

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM