Search code examples
javaexceptiontry-catchunreachable-codecatch-block

Unreachable code with multiple catch statements


Why does line 2 compile while line 3 does not? spit() throws a HurtException that has already been caught on line 1, so any checked exception that comes afterwards should be unreachable. If I delete line 2, line 3 will remain reachable. Exceptions are not exempt from compile-time checking. Thanks in advance for clarifying this for me.

public class Ape {
    public void run() {
        try {
            spit();
        } catch (HurtException e) { //line 1
            System.out.println("f");
        } catch (LimpException ex) { //line 2: Unreachable, HurtException already caught
            System.out.println("e");
        } catch (Exception ee) {     //line 3: Compiles, why?
            System.out.println("r");
        }
    }

    public static void main(String[] args) {
        new Ape().run();
    }

    public void spit() throws HurtException {
        throw new HurtException();
    }

    class LimpException extends Exception {
    }

    class HurtException extends LimpException {
    }
}

Solution

  • The compiler only "knows" about HurtException that could be thrown from spit() since you explicitly defined it that way. Adding LimpException to the throws part of your method signature should satisfy the compiler:

    public void spit() throws HurtException, LimpException {
        throw new HurtException();
    }
    

    Anyway, if the method doesn't really throw LimpException itself, you basically just make your code harder to read.