Originally posted by Valentin Crettaz:
The compiler error you are getting is just because method test in B doesn't throw any IOException and thus there is nothing to catch.
An overriding method doesn't need to throw the Exception thrown by the overridden method. The only thing it cannot do is throw "more" Exceptions than the overridden method throws.
In clear, an overriding method may throw:
- the same Exception as the overridden method
- a subclass of it
- a RuntimeException or its subclasses
- or nothing
Here, method test in B fulfills those requirements (the last one) so there is no problem. The only problem is that you enclose the invocation to test in a try-catch block and the compiler doesn't like it because there won't be any IOException thrown from method test in class B.
Now the tricky part is this:
If instead of having
B myref = new B();
A myref = new B();
then the try-catch is mandatory because you may well create an instance of A. The compiler doesn't know that you create an instance of B and requires the try-catch block in the case you have an object of type A and you invoke method test on it (which may throw an IOException).
I hope that clears your doubts.
How much do I owe you?
Your explanations and comments are extremely helpful and very easy to understand.
My bad - I changed IOException to Exception.
Gotta get my class path straightened out!!!