我有以下课程:
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?
谢谢!
答案 0 :(得分:4)
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");
}
答案 1 :(得分:0)
编译错误是因为应该最后捕获更广泛的异常。想象一个异常对象就像一个球被放置在金字塔的不同层次(金字塔板堆叠)上。更窄的异常(子类型)被捕获到底部的顶部和更广泛的(超类)。这不会给出编译错误。
catch (ArithmeticException e) {
System.out.println("Trying to divide by 0 is not ok.");
}catch (RuntimeException e) {
System.out.println("Runtime exception");
}
答案 2 :(得分:0)
当然ArithmeticException是RuntimeException的子集 算术异常是一个错误,当一个"错误"算术情况发生。这通常发生在 在运行期间程序内发生数学或计算错误。 但是如果你用两个类捕获异常,catch优先级必须是自上而下的,并且错误将被抛出到reanlated异常。
下面的代码将抛出ArithmeticException:
public static void main(String[] args) {
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");
}
}
下面的代码将抛出RuntimeException:
public static void main(String[] args) {
try {
int div = Integer.parseInt(args[0]);
int result = 1/div;
System.out.println(result);
}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");
}
}