Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exception in the case of Overriding

Tags:

java

As we know that in the case if method overriding If child class method throws some checked exception then compulsory parent class method should throw same checked exception or its parent class exception otherwise we will get compile error. But there is no rule on un-checked exception.

But if assume that Java allows parent class method to have checked exception which is child to the child class method checked exception.

Can some one please why this is not allowed in the Java.


Let put the question in a different way :

you have class A -

class A {

    public void doStuff() throws SQLException {

    }
}

and class B extends A -

class B extends A {

    public void doStuff() throws Exception {

    }
}

It will throw exception during compilation because of violation of the method's contract.

Assume that the Java would allows this then what would be the consequences ?

like image 944
Anish Avatar asked Sep 27 '14 11:09

Anish


People also ask

What are the 3 types of exceptions?

There are three types of exception—the checked exception, the error and the runtime exception.

Can we override exceptions?

According to the 3rd rule, if the super-class method throws certain exception, you can override it without throwing any exception.

What are the conditions for overriding?

Instance methods can be overridden only if they are inherited by the subclass. A method declared final cannot be overridden. A method declared static cannot be overridden but can be re-declared. If a method cannot be inherited, then it cannot be overridden.

Can child class throws an exception?

The child class constructor can throw any unchecked exception without looking for a parent class constructor.


1 Answers

I suppose you are asking why I cannot do this:

class Parent {
    void doStuff() throws FileNotFoundException {

    }
}

class Child extends Parent {
    @Override
    void doStuff() throws IOException {

    }
}

This is simple, what happens when I do:

final Parent parent = new Child();

try {
    parent.doStuff();
} catch (FileNotFoundException e) {
    e.printStackTrace();
}

And the Child decides to throw a, say SocketException?

I, correctly, try and catch FileNotFoundException from the call parent.doStuff but this will not catch the SocketException.

How I have an uncaught checked exception. This is not allowed.

If I specifically try and catch SocketException this will result in a compiler error as SocketException is not declared as thrown from Parent.doStuff.

The only way to solve this in the general case would be to always catch Exception as any child class can declare that it throws a more general type and bypass my catch. This is obviously not ideal.

like image 129
Boris the Spider Avatar answered Oct 16 '22 08:10

Boris the Spider