爲什麼此代碼不打印「d」。爲什麼它不會進入RunTimeException的catch塊?異常鏈如何在我的代碼中工作?
public static void main(String[] args) {
System.out.println("a");
try {
System.out.println("b");
throw new IllegalArgumentException();
} catch (IllegalArgumentException e) {
System.out.println("c");
throw new RuntimeException();
}catch (RuntimeException e) {
System.out.println("d");
throw new RuntimeException();
}finally{
System.out.println("e");
throw new RuntimeException();
}
}
該程序的輸出是
a
b
c
e
Exception in thread "main" java.lang.RuntimeException
編輯:投擲拋出:IllegalArgumentException後,它前進到對應的catch程序塊和打印 'C'。之後,因爲我們沒有在RuntimeException中捕獲異常,所以它不會再進一步。但既然保證了我們去了finally塊,它會打印'e',然後拋出RunttimeException。如果代碼類似於以下內容,則會拋出RuntimeException(「2」)。如果我們最後在內部註釋異常,它會拋出RuntimeException(「1」)。
public static void main(String[] args) throws InterruptedException {
System.out.println("a");
try {
System.out.println("b");
throw new IllegalArgumentException();
} catch (IllegalArgumentException e) {
System.out.println("c");
throw new RuntimeException("1");
}catch (RuntimeException e) {
System.out.println("d");
throw new RuntimeException();
}finally{
System.out.println("e");
throw new RuntimeException("2");
}
}