look at the next code lines please:
public void methodBla(){
try{
system.out.println(2/0);
{
catch(MyArithmeticException me){
system.out.println("Error: My exception");
}
catch(Exception a){
system.out.println("Error: general exception");
}
}
I don't understand why, when I'm trying to catch an ArithmeticException with my customize class: MyArithmeticException which extends ArithmeticException.
Public class MyArithmeticException extends ArithmeticException{
public MyArithmeticException(String str){
super("My Exception " + str);
}
}
MyArithmeticException doesnt catch it, its only catch the second "catch"(catch(Exception a)).
Thanks Z
It is simple, because the statement 2/0
doesn't throw a MyArithmeticException
. It throws ArithmeticException
and since you didn't catch ArithmeticException
, it is catched by the second catch.
The java language doesn't know if you want to derive your own exception type from any language defined exception. So if you need to throw your own type you should catch it and re-throw it as a ArithmeticException
:
public void methodBla(){
try{
try{
system.out.println(2/0);
catch(ArithmeticException e){
throw new MyArithmeticException(e);
}
}
catch(MyArithmeticException me){
system.out.println("Error: My exception");
}
catch(Exception a){
system.out.println("Error: general exception");
}
}
Good Luck.