Skip to content

Instantly share code, notes, and snippets.

@raykolbe
Created September 5, 2016 16:41
Show Gist options
  • Save raykolbe/e09b9e8775d9171da4a0313dff8ab9e7 to your computer and use it in GitHub Desktop.
Save raykolbe/e09b9e8775d9171da4a0313dff8ab9e7 to your computer and use it in GitHub Desktop.
Java 8 Unreachable code produces warning not error - confusing

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...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment