Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If parent method throws checked exception, then is it compulsory to throw the same exception in child class?

Tags:

java

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?

like image 347
Amit2311 Avatar asked Feb 13 '23 00:02

Amit2311


1 Answers

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.

like image 119
Jon Skeet Avatar answered Feb 15 '23 10:02

Jon Skeet