我有以下课程:
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吗?
谢谢!
发布于 2014-12-16 03:09:14
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");
}发布于 2014-12-16 03:10:11
编译器错误是因为更广泛的异常应该被捕获,last.Imagine是一个异常对象,类似于在金字塔(金字塔板堆栈)的不同级别上抛下的一个球,.The更窄的异常(子类型)被捕获在顶部,而bottom.This的更宽的(超类)不会给出编译错误。
catch (ArithmeticException e) {
System.out.println("Trying to divide by 0 is not ok.");
}catch (RuntimeException e) {
System.out.println("Runtime exception");
}发布于 2014-12-16 03:51:50
当然,ArithmeticException是RuntimeException的一个子集。
算术异常是在出现“错误”算术情况时抛出的错误。这通常发生在运行时程序中出现数学或计算错误时.但是,如果两个类都捕获异常,则捕获优先级必须是自上而下的,错误将抛出以实现异常。
下面的代码将抛给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");
}
}https://stackoverflow.com/questions/27496876
复制相似问题