Helenesh
Helenesh

Reputation: 4349

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 {
    }
}

Upvotes: 2

Views: 885

Answers (2)

Sva.Mu
Sva.Mu

Reputation: 1131

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.

Upvotes: 3

Konstantin Yovkov
Konstantin Yovkov

Reputation: 62864

Line 3 compiles, because Exception is a superclass for all RuntimeExceptions and if such is thrown, it will be handled (at Runtime) with the body of (catch Exception) block.

The compiler can't determine if such exception will be thrown at Runtime and thus, doesn't mark it as unreachable

Upvotes: 2

Related Questions