Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java : How to override a method and throw exception?

I'm trying to override a method, with throwing an exception:

class A {

    public doSomething(){
        // some of logic
    }

}


class B extends A {

    public doSomething() throws MyCustomizedException {
        try {
             // some of logic
        } catch(ExceptionX ex ) {
             throw new MyCustomizedException(" Some info ", ex);
        }
    }      
}

But I get this compile time error :

Exception MyCustomizedException is not compatible with throws clause in A

The two constraints are :

  • Using the same name of the function and the same arguments if they exist: doSomething()
  • Throwing my customized exception

How can I get rid of the exception?

Thank you a lot.

like image 936
user3169231 Avatar asked Feb 11 '26 23:02

user3169231


1 Answers

Cannot be done.

When you override a method, you can't break the original contract and decide to throw a checked exception.

You can make MyCustomizedException unchecked. You can throw it, but you can't require that users handle it the way you can with a checked exception. The best you can do is add it to the javadocs and explain.

like image 141
duffymo Avatar answered Feb 13 '26 16:02

duffymo