exception and exception…
What is the result of compiling the code below:
class A{
public void x(){}
public void y(){}}
class B extends A{ //1public void x() throws NullPointerException{} //2
public void y() throws java.io.IOException {} //3}
The choices:
- code compiles without exception
- compilation exception at 1
- compilation exception at 2
- compilation exception at 3
if you’re an experienced java programmer or the jls is under your pillow you probably know the answer. for the others: the above code causes a compile-time error at 3. the explanation is given in the jls:
“A method that overrides or hides another method (§8.4.8), including methods that implement abstract methods defined in interfaces, may not be declared to
throw more checked exceptions than the overridden or hidden method.”
that is, if you declared that y throws no checked exceptions then you can’t override y in B to throw IOException (which is a checked exception). that’s not the same with unchecked exceptions (they are actually not mentioned in the jls): you’re free to declare NullPointerException to be thrown.
3 years ago