Java Exception as checked Exception but not required to be thrown in trycatch

前端 未结 2 498
半阙折子戏
半阙折子戏 2021-01-20 00:37

I have this snippet.

public final class StackOverflow{
   class MyException extends Throwable{
   }
   private void a(){
       try{
       }catch(MyExceptio         


        
2条回答
  •  抹茶落季
    2021-01-20 00:53

    It is explained in the Java Language Specification (emphasis in bold):

    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.

    I guess the rationale behind this is that: MyException is indeed a checked exception. However, unchecked exceptions also extend Exception (transitive inheritance from RuntimeException), so having a catch include the Exception class is excluded from the exception analysis done by the compiler.

提交回复
热议问题