抛出异常时会发生什么?
What happens when an exception is thrown?
我无法理解抛出异常时会发生什么。
抛出的异常会怎样?什么处理它以确保程序不会崩溃?
例如,在这个来自 this tutorial 的示例中,将如何处理抛出的 ArithmeticException
?
static int remainder(int dividend, int divisor)
throws DivideByZeroException {
try {
return dividend % divisor;
}
catch (ArithmeticException e) {
throw new DivideByZeroException();
}
}
您 link 的教程强调了 Java 中异常类型的重要区别,即异常是 checked 还是未选中.
checked 异常是一种要求您作为开发人员要么捕获它(即处理它),要么声明它被抛出并在上游处理的异常。期望您可以从这些异常中恢复。
unchecked 异常是在应用程序自然执行期间可能会或可能不会出现的异常,并且可能不会引入应用程序恢复的自然方式。抓住它们通常是不受欢迎的,因为它通常表明设计不佳(你允许零进入除法运算,这是非法的论点!)。
在这种情况下,因为方法 remainder
声明它正在抛出一个 DivideByZeroException
,它的所有上游调用者 必须 处理它的异常:
public static void main(String[] args) {
try {
NitPickyMath.remainder(1, 0);
} catch (DivideByZeroException e) {
e.printStackTrace();
}
}
...或通过:
public static void main(String[] args) throws DivideByZeroException {
NitPickyMath.remainder(1, 0);
}
后一种形式的注意事项是没有任何东西会处理异常,这会导致应用程序崩溃。
...what will deal with the ArithmeticException
that is thrown?
您已经正在 处理它,方法是将它放在catch
块中。您只是重新抛出一个已检查的异常来处理将 1 除以 0 所导致的实际错误。
我无法理解抛出异常时会发生什么。
抛出的异常会怎样?什么处理它以确保程序不会崩溃?
例如,在这个来自 this tutorial 的示例中,将如何处理抛出的 ArithmeticException
?
static int remainder(int dividend, int divisor)
throws DivideByZeroException {
try {
return dividend % divisor;
}
catch (ArithmeticException e) {
throw new DivideByZeroException();
}
}
您 link 的教程强调了 Java 中异常类型的重要区别,即异常是 checked 还是未选中.
checked 异常是一种要求您作为开发人员要么捕获它(即处理它),要么声明它被抛出并在上游处理的异常。期望您可以从这些异常中恢复。
unchecked 异常是在应用程序自然执行期间可能会或可能不会出现的异常,并且可能不会引入应用程序恢复的自然方式。抓住它们通常是不受欢迎的,因为它通常表明设计不佳(你允许零进入除法运算,这是非法的论点!)。
在这种情况下,因为方法 remainder
声明它正在抛出一个 DivideByZeroException
,它的所有上游调用者 必须 处理它的异常:
public static void main(String[] args) {
try {
NitPickyMath.remainder(1, 0);
} catch (DivideByZeroException e) {
e.printStackTrace();
}
}
...或通过:
public static void main(String[] args) throws DivideByZeroException {
NitPickyMath.remainder(1, 0);
}
后一种形式的注意事项是没有任何东西会处理异常,这会导致应用程序崩溃。
...what will deal with the
ArithmeticException
that is thrown?
您已经正在 处理它,方法是将它放在catch
块中。您只是重新抛出一个已检查的异常来处理将 1 除以 0 所导致的实际错误。