Reputation: 69
I am reading the book of Sierra Kathe SCJP 6 and I fell into a contradiction:
The overriding method can throw narrower or fewer exceptions. Just because an overridden method "takes risks" doesn't mean that the overriding subclass' exception takes the same risks. Bottom line: an overriding method doesn't have to declare any exceptions that it will never throw, regardless of what the overridden method declares.
Mean that if the overriding method can throw an exception if the same method from the subclass threw the exeption, but after testing I found that its impossible for any exception as Exception or SQLException or IOException. But for some exception such NullPointerException it works perfectly
Upvotes: 1
Views: 121
Reputation: 59111
An overriding method can't broaden the set of checked exceptions that the base declaration throws. Because if you are calling the method, as declared in the base class, you can't handle exceptions thrown by the subclass that you don't know about.
A NullPointerException
is an unchecked exception. Any method can throw it; it doesn't need to be in a throws
declaration.
Upvotes: 3
Reputation: 200166
Any overriding method may declare to throw any unchecked exception:
class Parent {
abstract void m1() throws IOException {}
}
class Child {
@Override void m1() throws IllegalArgumentException {}
}
Declared unchecked exceptions do not enter the method's signature and are generally ignored by the compiler. They are allowed nevertheless because it may offer advantages for the purpose of documentation.
The above rule makes sense because a method may throw any unchecked exception whether it declares it or not.
Upvotes: 0
Reputation: 726699
The book talks about checked exceptions, the only ones that must be declared.
Any exception derived from RuntimeException
is considered unchecked, meaning that you can throw it without declaring.
Upvotes: 1