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 ?
There are three types of exception—the checked exception, the error and the runtime exception.
According to the 3rd rule, if the super-class method throws certain exception, you can override it without throwing any exception.
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.
The child class constructor can throw any unchecked exception without looking for a parent class constructor.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With