简体   繁体   中英

Why customize Exception doesn't catch this? (JAVA)

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: My ArithmeticException 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.

The problem is that an Arithmetic exception would be thrown. Not a "MyAritmeticException" so it cant be caught by the first catch clause, so it results to the second catch clause.

In other words, 2/0 will throw an AritmeticException which is the superclass of your exception thus it will not triger the MyArithmeticException catch block because thats a subclass.

If you want to customise the message of the exception you can do that in the catch statement, where you can get the message by Exception#getMessage() or Exception#getLocalizedMessage(); (the difference of the two can be found here )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM