gpt4 book ai didi

Java - 为什么不调用 ArithmeticException 类的子类?

转载 作者:行者123 更新时间:2023-12-02 08:45:31 25 4
gpt4 key购买 nike

我想修改ArithmeticException输出消息。因此,为此我做了一些实验。我通过 ExtenderClass 类扩展了 ArithmeticException 类。这个问题的重点不仅在于找到修改 ArithmeticException 异常消息的解决方案,还在于说明为什么下面的某些情况可以按预期工作,但有些情况却不能?以下是案例及其输出:

情况1:

// Both the classes are in the same file 'MyClass.java'
class MyClass{
public static void main(String args[]){

int a,b,c;
a = 1;
b = 0;

try{
c = a / b;
}catch(ArithmeticException e){
System.out.println("I caught: " + e);
}

}
}

class ExtenderClass extends ArithmeticException{
// ...
}

输出:

I caught: java.lang.ArithmeticException: / by zero

结果:按预期工作正常。

<小时/>

情况2:

// Both the classes are in the same file 'MyClass.java'
class MyClass{
public static void main(String args[]){

int a,b,c;
a = 1;
b = 0;

try{
c = a / b;
}catch(ExtenderClass e){
System.out.println("I caught: " + e);
}

}
}

class ExtenderClass extends ArithmeticException{
// ...
}

输出:

Exception in thread "main" java.lang.ArithmeticException: / by zero
at MyClass.main(MyClass.java:9)

结果:表示 throw/catch 未触发。为什么 ExtenderClass 没有被触发?事实上它扩展了 ArithmeticException 类?

<小时/>

情况3:

// Both the classes are in the same file 'MyClass.java'
class MyClass{
public static void main(String args[]){

int a,b,c;
a = 1;
b = 0;

try{
c = a / b;
throw new ArithmeticException();
}catch(ArithmeticException e){
System.out.println("I caught: " + e);
}

}
}

class ExtenderClass extends ArithmeticException{
// ...
}

输出:

I caught: java.lang.ArithmeticException: / by zero

结果:按预期工作正常。

<小时/>

情况4:

// Both the classes are in the same file 'MyClass.java'
class MyClass{
public static void main(String args[]){

int a,b,c;
a = 1;
b = 0;

try{
c = a / b;
throw new ExtenderClass();
}catch(ExtenderClass e){
System.out.println("I caught: " + e);
}

}
}

class ExtenderClass extends ArithmeticException{
// ...
}

输出:

Exception in thread "main" java.lang.ArithmeticException: / by zero
at MyClass.main(MyClass.java:9)

结果:表示 throw/catch 未触发。为什么 ExtenderClass 没有被触发?事实上它扩展了 ArithmeticException 类?

<小时/>

为什么扩展ArithmeticExceptionExtenderClass类没有被触发?但是当我直接使用 ArithmeticException 时,它会被触发。

最佳答案

虽然您已将自定义异常声明为 ArithmeticException 的子类,但您无法让 a/b 抛出自定义异常。 JLS 指定(整数)除以零将抛出 ArithmeticException;请参阅JLS 15.17.2第 3 段。

由于抛出的异常是 ArithmeticException,因此您将无法将其捕获为自定义异常。

try {
c = a / b;
} catch (ExtenderClass ex) {
...
}

将捕获ExtenderClassExtenderClass的子类。 ArithmeticException 不是 ExtenderClass 的子类,因此上面的不会捕获它。

<小时/>

您创建 ExtenderClass 的原因是...

I want to modify the ArithmeticException output message.

您最好编写一些特殊情况的代码,以便在打印时用不同的消息替换“/零”消息。

或者....

try {
c = a / b;
} catch (ArithmeticException ex) {
thrown new ExtenderClass("Division by zero is cool!, ex);
}

关于Java - 为什么不调用 ArithmeticException 类的子类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53984093/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com