如果这个问题看起来太愚蠢或者基本不好,我提前表示歉意。但谷歌搜索没有让我知道这一点。应该抛出或捕捉哪个异常
的代码很简单:
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时提到一个异常类型?这种类型代表什么? –