如果這個問題看起來太愚蠢或者基本不好,我提前表示歉意。但谷歌搜索沒有讓我知道這一點。應該拋出或捕捉哪個異常
的代碼很簡單:
public class Average3 {
public static void main(String[] args) {
try {
printAverage(100, 0);
} catch (ArithmeticException ae) {
ae.printStackTrace();
System.out.println("Exception handled in " +
"main().");
}
System.out.println("Exit main().");
}
public static void printAverage(int totalSum, int totalNumber) {
try {
int average = computeAverage(totalSum, totalNumber);// (8)
System.out.println("Average = " +
totalSum + "/" + totalNumber + " = " + average);
} catch (IllegalArgumentException iae) {
iae.printStackTrace();
System.out.println("Exception handled in " +
"printAverage().");
}
System.out.println("Exit printAverage().");
}
public static int computeAverage(int sum, int number) {
System.out.println("Computing average.");
return sum/number;
}
}
輸出:
Computing average.
java.lang.ArithmeticException:/by zero
at Average3.computeAverage(Average3.java:30)
at Average3.printAverage(Average3.java:17)
at Average3.main(Average3.java:6)
Exception handled in main().
Exit main().
這裏我期待拋出:IllegalArgumentException由於被0除發生在computeAverage其通過printAverage調用。在我看來,try語句應該跳過,並且在這一點上它應該移動到註冊IllegalArgumentException的catch處。
我其實有一個陰沉的瞭解,但我想知道到底發生了什麼,爲什麼。我一直在絞盡腦汁。
感謝您的幫助。
爲什麼它應該移動到'IllegalArgumentException'的'catch'? –
,因爲我認爲try-catch塊和try語句失敗,它應該移動到捕獲 – user6556673
爲什麼你認爲你在使用catch時提到一個異常類型?這種類型代表什麼? –