1

I need to change the return message of the method getMessage() , for instance, i have an ArithmeticException, and when I write:

try{c=a/0;}
catch(ArithmeticException excep){System.out.println( excep.getMessage() );}

and I execut this code I have: / by zero.

So, I wanted to change this result by overwriting the getMesage method. I have created a new class called MyException that inherits from ArithmeticExceprtion and I override the methode getMessage, and after that I have changed the type of the exception in my last code from ArithmeticException to my new name class MyException:

public class MyException extends ArithmeticException{
    @override
    public String getMessage(){
       retun "new code message";}

} and I have changed the first code, I have wrotten:

try{c=a/0;}
catch(MyException excep){System.out.println( excep.getMessage() );}

and when I have executed this code, I had the same error's message as if I didn't catch the exception:

Exception in thread "main" java.lang.ArithmeticException: / by zero
     at main.test.main(Test.java:33)

So, my question is: how can I change the message of the methode getMessage() ?

Amine
  • 19
  • 1
  • 4

1 Answers1

1

You have extended the ArithmeticException with a new class called MyException. But the statement c = a / 0; still throws ArithmeticException but never MyException itself, so your catch clause is not reached.

Note that normally you shouldn't catch runtime (unchecked) exceptions like ArithmeticException since it denotes a programming error. Also note that for checked exceptions, the compiler shows an error telling you that the statement would never throw that kind of exception, but in this case, MyException is an unchecked exception so the compiler is fine with it.

In your particular scenario, you cannot change the message of the exception since it will always be an ArithmeticException. But you can always print whatever message you want in the catch clause. Or you can wrap the statement in a method and let that method throw the subclass exception:

public void foo() throws MyException {
   try {
        c = a / 0;
   } catch (ArithmeticException excep) {
        // handle excep
        throw new MyException();
   }
}
M A
  • 71,713
  • 13
  • 134
  • 174
  • but we cannot add the block try/catch in the code of the function !?, we have to write it at the time when we call the function foo, isn't it @manouti ? – Amine Nov 13 '14 at 00:01