我正在學習例外,我發現你可以抑制例外。我在 stackoverflow 上閱讀了許多示例,但它們仍然不能像在“try/finally”情況下那樣作業:
public class MultipleExceptionsExample {
static class IOManip implements Closeable{
@Override
public void close() {
throw new RuntimeException("from IOManip.close");
}
}
public static void main(String[] args) {
try(IOManip ioManip = new IOManip()){
throw new RuntimeException("from try!");
}catch(Exception e){
throw new RuntimeException("from catch!");
}finally{
throw new RuntimeException("from finally!");
}
}
}
正如許多人所解釋的那樣,我應該得到所有行:“java.lang.RuntimeException:from finally!” (是的,我愿意)
洗掉 finally 塊我應該得到:“java.lang.RuntimeException:from catch!” (是的,我愿意)
洗掉 catch 塊我應該得到:
Exception in thread "main" java.lang.RuntimeException: from try!
Suppressed: java.lang.RuntimeException: from IOManip.close
我從不這樣做!為什么?我錯過了什么?
通過洗掉 catch 塊,我應該看到 try 訊息,但我得到了這個:
Exception in thread "main" java.lang.RuntimeException: from finally!
at it.core.MultipleExceptionsExample.main(MultipleExceptionsExample.java:18)
非常感謝。
uj5u.com熱心網友回復:
塊中的回傳或拋出finally會導致任何其他回傳(或拋出)的結果被忽略。
除非你真的知道自己在做什么,return否則不要這樣做。throwfinally
應該注意的是,Java Throwables 有一個“抑制”例外的概念:你可以呼叫你捕獲addSuppressed的例外;如果在主體中發生例外并且在關閉資源時,Throwable這是使用try-with-resources塊自動完成的;但這不會發生在一個塊中。finally
uj5u.com熱心網友回復:
這是因為finally塊總是會執行。是否捕獲例外并不重要。為了更好地理解它,請嘗試以下代碼:
public static void main(String[] args) {
try (IOManip ioManip = new IOManip()) {
System.out.println("Try!");
throw new RuntimeException("from try!");
} finally {
System.out.println("Finally!");
}
}
請記住,從 finally 塊回傳或拋出不是一個好習慣,您應該避免這樣做。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/449323.html
