If a method declares to throw a given exception, the overriding method in a subclass can only declare to throw that exception or its subclass. This is because of Polymorphism. So imo, your thinking is correct.
Java Certification: How to override methods that define a throws exception?
Frage
Can anyone confirm the following in regards to methods that define exceptions thrown when method overriding? I want to be sure I understand it clearly.
Given the following code:
class A
{
public void doStuff() throws IllegalArgumentException{}
}
class B extends A
{
public void doStuff() throws NumberFormatException{}
}
class C extends A
{
public void doStuff() throws Exception{}
}
Only class A and B should compile and not class C. When overriding a method you can narrow the thrown class, but cannot widen it like in class C. The reason behind this I believe is the example in the following code:
class D
{
doIt(A a)
{
try
{
a.doStuff();
}
catch(IlligalArgumentException e){}
}
}
Class A could be extended any number of times and so the doStuff() method can also potentially be overriden any number of times, but regardless, the try catch above will always catch the exception.
But if widening were allowed, the above code could potentially miss the exception being thrown and there would be unexpected result in the application.
Is this the correct thinking? Is there anything else I'm missing?
Thanks
Lösung
Andere Tipps
For reference, the Java Language Specification says
A method that overrides or hides another method, including methods that implement abstract methods defined in interfaces, may not be declared to throw more checked exceptions than the overridden or hidden method.
and
More precisely, suppose that
B
is a class or interface, andA
is a superclass or superinterface ofB
, and a method declarationn
inB
overrides or hides a method declarationm
inA
. Then:
If
n
has a throws clause that mentions any checked exception types, thenm
must have a throws clause, or a compile-time error occurs.For every checked exception type listed in the throws clause of
n
, that same exception class or one of its supertypes must occur in the erasure (§4.6) of the throws clause ofm
; otherwise, a compile-time error occurs.If the unerased throws clause of
m
does not contain a supertype of each exception type in the throws clause ofn
, a compile-time unchecked warning occurs.
So the rule applies to checked exception types, not unchecked.