I want to modify the ArithmeticException
output message. So, for that i did few experiments. I extended the ArithmeticException
class byExtenderClass
class. The point of this question is not only to find the solutions to modify the ArithmeticException
exception message but also to tell why some of cases below are working as expected but some are not? Following are the cases along with their outputs:
Case 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{
// ...
}
Output:
I caught: java.lang.ArithmeticException: / by zero
Result: Works fine as expected.
Case 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{
// ...
}
Output:
Exception in thread "main" java.lang.ArithmeticException: / by zero
at MyClass.main(MyClass.java:9)
Result: Means that the throw/catch
is not fired. Why the ExtenderClass
is not fired? In fact its extending the ArithmeticException
class?
Case 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{
// ...
}
Output:
I caught: java.lang.ArithmeticException: / by zero
Result: Works fine as expected.
Case 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{
// ...
}
Output:
Exception in thread "main" java.lang.ArithmeticException: / by zero
at MyClass.main(MyClass.java:9)
Result: Means that the throw/catch
is not fired. Why the ExtenderClass
is not fired? In fact its extending the ArithmeticException
class?
Why the ExtenderClass
class that extends the ArithmeticException
is not fired? But when i use the ArithmeticException
directly, it gets fired.