Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does multi-catch RuntimeException compile but multi-catch Exception does not?

In this example, the 2nd catch block is unreachable and therefore my code does not compile. However, if I make LimpException extend RuntimeException instead of Exception, it compiles without any trouble. Why?

public class Finals {

  public void run() {
    try {
      spit();
    } catch (HurtException e) {
      System.out.println("");
    } catch (LimpException ex) { // does not compile, unreachable code
      System.out.println("");
    }
  }

  public void spit() throws HurtException { // method that throws the Exception
  }

  public static void main(String... args) {
  }
}

class LimpException extends Exception { // extends Exception vs extends
                                        // RuntimeException
}

class HurtException extends LimpException {
}
like image 451
Helenesh Avatar asked Aug 31 '15 18:08

Helenesh


1 Answers

According to the JLS §11.2:

The unchecked exception classes (§11.1.1) are exempted from compile-time checking.

That's pretty simple. Even though that code block is still unreachable, the compiler simply doesn't check.

In your example, LimpException cannot be thrown from the try statement body that isn't already caught by the catch LimpException catch block. This is banned by JLS §11.2.3:

It is a compile-time error if a catch clause can catch checked exception class E1 and it is not the case that the try block corresponding to the catch clause can throw a checked exception class that is a subclass or superclass of E1, unless E1 is Exception or a superclass of Exception.

It is a compile-time error if a catch clause can catch (§11.2) checked exception class E1 and a preceding catch clause of the immediately enclosing try statement can catch E1 or a superclass of E1.

like image 168
durron597 Avatar answered Nov 09 '22 00:11

durron597