This code has an unreachable catch block and the Java compiler does not produce an error it produces a warning. I can't figure out why. Please help!
class ParentException extends Exception {}
class ChildException extends ParentException {}
public class Scratch {
public static void foo() throws ChildException {}
public static void main(String args[]) {
try {
foo();
} catch (ChildException e) {
} catch (ParentException e) {
}
}
}
Compiling the above code produces:
warning: unreachable catch clause
} catch (ParentException e) {
^
thrown type ChildException has already been caught
1 warning
According to JLS §14.21 any unreachable code should result in a compile-time error.
Excerpt explaining what makes a catch block reachable.
A catch block C is reachable iff both of the following are true:
- Either the type of C's parameter is an unchecked exception type or Exception or a superclass of Exception, or some expression or throw statement in the try block is reachable and can throw a checked exception whose type is assignable to the type of C's parameter. (An expression is reachable iff the innermost statement containing it is reachable.)
See §15.6 for normal and abrupt completion of expressions.
There is no earlier catch block A in the try statement such that the type of C's parameter is the same as or a subclass of the type of A's parameter.
The Block of a catch block is reachable iff the catch block is reachable.
I have read the following and still have not found a reason why this is a warning vs. error.
https://coderanch.com/t/651798/ocajp/certification/Mock-exam-wrong-answer-Java http://docs.oracle.com/javase/specs/jls/se8/html/jls-14.html#jls-14.21 http://stackoverflow.com/questions/2141029/unreachable-code-error-vs-dead-code-warning-in-java-under-eclipse http://stackoverflow.com/questions/5899849/java-unreachable-catch-block-compiler-error
and many more...