gpt4 book ai didi

Java,try-finally 不带 catch

转载 作者:行者123 更新时间:2023-11-30 06:55:29 24 4
gpt4 key购买 nike

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

}

在 main 中我处理了异常:

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

主要是我能捕获它。这是正常行为吗?

最佳答案

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

对于 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()

获取

关于Java,try-finally 不带 catch,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41927159/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com