Reputation: 103
why overriding methods can throw unchecked exception in java ?
Why can't overriding methods throw exceptions broader than the overridden method? Is not my question . I just want to know why Overriding methods CAN throw unchecked exception while cannot throw checked exception.
Upvotes: 1
Views: 1901
Reputation: 691835
Let's say a base class has the following method:
int foo() throws IOException;
That means that the method can
Now let's override this method in a subclass. The subclass must obey the contract of the base method, so it can
What it can't do, though, is
Upvotes: 3
Reputation: 15212
why overriding methods can throw unchecked exception in java ?
Any method in Java can throw an unchecked exception. An overriding method is also a method so it gets the same privileges as other methods when it comes to unchecked exceptions.
I just want to know why Overriding methods CAN throw unchecked exception while cannot throw checked exception
The last part of your sentence is incorrect. An overriding method can throw both checked an unchecked exceptions. I believe the questions that you are trying to ask are
Let's answer 1)
class Parent {
public void doSomething() { }
}
class Child extends Parent {
public void doSomething()throws Exception { }
}
Let's assume that the above code was allowed. The client code would then look like this :
Parent p = new Child();
p.doSomething();
If there was no restriction on what checked exceptions could be thrown by an overriden method, there would be no compilation error in the above code. The compiler has no idea that doSomething
in Child
can actually throw
a checked Exception
. The throw Exception
clause for the doSomething
method in Child
would kind of be pointless since the programmer is not required to handle the checked exception.
Let's answer 2)
The Oracle tutorial has a nice write-up that is useful in the context of your question :
Runtime exceptions represent problems that are the result of a programming problem, and as such, the API client code cannot reasonably be expected to recover from them or to handle them in any way. Such problems include arithmetic exceptions, such as dividing by zero; pointer exceptions, such as trying to access an object through a null reference; and indexing exceptions, such as attempting to access an array element through an index that is too large or too small.
Runtime exceptions can occur anywhere in a program, and in a typical one they can be very numerous. Having to add runtime exceptions in every method declaration would reduce a program's clarity. Thus, the compiler does not require that you catch or specify runtime exceptions (although you can).
Since the programmer is not obliged to catch a RuntimeException
that is thrown by a method, putting the same restriction as checked exceptions for unchecked exceptions in case of overriden methods would be pointless.
Upvotes: 1