class X extends Exception {
}
class Y extends X {
}
class Z extends Y {
}
public class Test {
static void aMethod() throws Z {
throw new Z();
}
public static void main(String[] args){
int x = 10;
try {
aMethod();
}
catch(X e) {
System.out.println(“Error X”);
}
catch(Y e) {
System.out.println(“Error Y”);
}
}
}
What is the output?
(A) The exception will go uncaught by both catch
blocks
(B) It will print “Error X”
(C) It will print “Error Y”
(D) It does not compile 😉
The second catch block is unreachable.
If you turn it around, and catch
Yfirst you still should get a compiler warning, as Z is a checked exception and the compiler will detect that only the first catch clause can be reached. But the example will work, and “Error Y” will be printed.Java always evaluates the catch clauses in the order they are defined, which is the reason you should define the most specific exceptions first, in this case
catch (Y y)should come beforecatch (X x).EDIT: In the first version I assumed that the compiler error “Unreachable code” can be turned off with special compiler settings. Thanks to Marko Topolnik for the clarification.