我想修改ArithmeticException
输出消息。所以,为此我做了一些实验。我一个接一个地扩展了ArithmeticException
课程ExtenderClass
。这个问题的重点不仅是要找到修改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
结果:按预期工作正常。
案例二:
// 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
课程?
为什么ExtenderClass
扩展的类ArithmeticException
没有被解雇?但是当我ArithmeticException
直接使用时,它会被解雇。