Given:
static class A {
void process() throws Exception { throw new Exception(); }
}
static class B extends A {
void process() { System.out.println("B "); }
}
public static void main(String[] args) {
A a = new B();
a.process();
}
In this question, when I call a.process()
, it will give me a compile time error, saying, "Unhandled exception must be handled". But, if the parent method is throwing any checked exception, its not necessary to handle that exception in the child if we are overriding the parent's implementation.
Why is the exception still checked?
The point is that the compiler doesn't know that you're calling an overridden method which doesn't throw any checked exceptions. When it sees:
a.process();
it doesn't "know" that the value of a
is actually a reference to an instance of B
. It could be a reference to an instance of A
(or an instance of another subclass), which would throw the exception.
If you want to use subclass-specific signatures, you need:
B b = new B();
instead. Then when the compiler sees
b.process();
it will look at how the method is declared in B
, not how it's declared in A
.
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