-1

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

Ziv Ru
  • 11
  • 2
  • 3
    That's because the implementation of division doesn't know about your custom exception type, and so will never throw an instance of it. Catch `ArithmeticException` instead. – Andy Turner Jan 31 '16 at 12:04
  • Because your exception `MyArithmeticException` is never thrown. – GiantTree Jan 31 '16 at 12:05

2 Answers2

2

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.

STaefi
  • 4,297
  • 1
  • 25
  • 43
0

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)

Community
  • 1
  • 1
fill͡pant͡
  • 1,147
  • 2
  • 12
  • 24