我有以下课程:
public class TryCatchExample {
public static void main(String[] args) {
try {
System.out.println(1/0);
}catch (RuntimeException e) {
System.out.println("Runtime exception");
} catch (ArithmeticException e) {
System.out.println("Trying to divide by 0 is not ok.");
}
finally {
System.out.println("The program will now exit");
}
}
}
编译器将引发以下错误:
TryCatchExample.java:10: error: exception ArithmeticException has already been caught
} catch (ArithmeticException e) {
^
1 error
为什么会发生这种情况? ArithmeticException是RuntimeException的子集,所以这会抛出RuntimeException还是ArithmeticException?
谢谢!
最佳答案
ArithmeticException
是RuntimeException
的子类,这意味着它已经由catch (RuntimeException e) ...
分支处理。
您可以重新排序分支,以便首先捕获ArithmeticException
,其他任何RuntimeException
都将落入下一个分支:
try {
System.out.println(1 / 0);
} catch (ArithmeticException e) {
System.out.println("Trying to divide by 0 is not ok.");
} catch (RuntimeException e) {
System.out.println("Runtime exception");
} finally {
System.out.println("The program will now exit");
}