Search code examples
javaexceptionunreachable-statement

The code clearly has an unreachable statement in it yet compiles - why?


The statement on Line 2 will never execute but the compiler doesn't complain:

class Test {

    public static void main(String[] args) throws Exception {
        throwE();
//        throw new Exception();  // Line 1
        doStuff();                // Line 2
    }

    static void throwE() throws Exception {
        System.out.println("Throwing an Exception");
        throw new Exception();
//        doStuff();              // Line 3
    }

    static void doStuff(){ System.out.println("Doing stuff"); }
}

On the other hand, uncommenting either Line 1 or Line 3 leads to the 'unreachable statement' compile-time error.

I wonder why the compiler is so inconsistent...


Solution

  • The compiler doesn't analyze any method call (such as throwE()) to find out whether it will always throw an exception, since that's not practical. There might be a chain of 10 (or a 100) method calls where the last method always throws an exception. Would you still expect the compiler to determine that any statement following throwE() is unreachable in such case?

    Only if the current method always throws an exception directly, any statements following the throw statement are deemed unreachable.