2 回答

TA貢獻1830條經驗 獲得超3個贊
順便說一句,正確的方法是ArithmeticException在需要時允許結束程序。
public class Exam {
private static void div(int i, int j) throws ArithmeticException {
System.out.println(i / j);
}
public static void main(String[] args) throws Exception {
div(5, 0);
}
}
更加干凈和清晰,異常提供了重要的調試信息,您需要這些信息來查找運行時錯誤。
我認為要捕獲第二個異常,您需要做的就是嵌套try. 您可以有多個catch相同的對象try,但它們都只能捕獲一個異常,它們不會級聯或按順序運行。要捕獲由 a 引發的異常,catch您需要另一個try塊。
private static void div(int i, int j) {
try { // NESTED HERE
try {
System.out.println(i / j);
} catch(ArithmeticException e) {
Exception ex = new Exception(e);
throw ex;
}
// THIS GOES WITH THE OUTER NESTED 'try'
} catch( Exception x ) {
System.out.println( "Caught a second exception: " + x );
}
}
但同樣,你不應該這樣做。允許拋出原始異常是更好的選擇。

TA貢獻1811條經驗 獲得超4個贊
我的結論:
此catch 語句處理一個異常:
try{
? ? stuff
}catch(OnlyThisException ex){
? ? throw ex;? ?//CHECKED EXCEPTION
}
此catch 語句也僅處理一個異常,而另一個則未處理:
try{
? ? stuff
}catch(OnlyThisException ex){
? ? Exception ex = new Exception(e);? //UNCHECKED! Needs catch block
? ? throw ex;? ?//CHECKED EXCEPTION
}
添加回答
舉報