user3169231
user3169231

Reputation: 257

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 :

How can I get rid of the exception?

Thank you a lot.

Upvotes: 2

Views: 2463

Answers (4)

Tim B
Tim B

Reputation: 41188

There is actually a way to do this - using composition rather than inheritance:

class B {
   A a = new A();
   void doSomething() throws MyException {
      a.doSomething();
      throw MyException();
   }
}

Of course by doing this your B no longer counts as an A so cannot be passed to anything expecting an A. You could use a B throughout your code though and just wrap As on demand.

Upvotes: 2

Tim B
Tim B

Reputation: 41188

The only way you can do this is to make the exception that you are throwing extend RuntimeException instead of Exception.

This way you will be able to throw it as you don't change the compact of the method, unfortunately the compiler will not automatically detect that you need to catch that exception but depending on how you are using it that may not be a problem.

Upvotes: 0

Ruchira Gayan Ranaweera
Ruchira Gayan Ranaweera

Reputation: 35557

This is not a overloading case. To overload you need methods with same signature but different argument list. This is Overriding, Use public doSomething() throws MyCustomizedException {} in class A if Class A can modify.

Now you can override with your current implementation for class B.

Upvotes: 0

duffymo
duffymo

Reputation: 308848

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.

Upvotes: 7

Related Questions