Search code examples
javaexceptionjls

How are RuntimeExceptions not checked by compiler, even though they extend Exception class?


When we create a CustomException by extending Exception class it is checked by compiler, but even though RuntimeExceptions extend Exception class are they not checked by the compiler.

How is this established in the compiler. I found a section in JLS stating why.

Why Runtime Exceptions are Not Checked
The runtime exception classes (RuntimeException and its subclasses) are exempted from compile-time checking because, in the judgment of the designers of the Java programming language, having to declare such exceptions would not aid significantly in establishing the correctness of programs. Many of the operations and constructs of the Java programming language can result in runtime exceptions. The information available to a compiler, and the level of analysis the compiler performs, are usually not sufficient to establish that such run-time exceptions cannot occur, even though this may be obvious to the programmer. Requiring such exception classes to be declared would simply be an irritation to programmers.

Is there something happens behind the scenes like in the case of marker interfaces.

I am looking for some source that can explain how it is done and also why there is no parent class for all checked exceptions?


Solution

  • Is there something happens behind the scenes like in the case of marker interfaces.

    The fact that RuntimeException is exempted from the rule that all subclasses of Exception are checked exceptions is simply part of the spec.

    How this exception to the rule is implemented is compiler dependent.