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

邮差的信 提交于 2020-01-11 09:22:46

问题


I have this snippet.

public final class StackOverflow{
   class MyException extends Throwable{
   }
   private void a(){
       try{
       }catch(MyException | Exception e){
       }
   }
}
exception StackOverflow.MyException is never thrown in body of corresponding try statement

I know that Exception is extending Throwable as well and also is a checked exception also MyException is extending Throwable which mades also a checked exception!

My question is why Exception is not required to be thrown in the try catch but MyException is? I think that both are checked exception so which is the difference??

Sorry if the question is simple.


回答1:


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.




回答2:


Exception extends from RuntimeException will considered as uncheched exception, so it's ok:

class MyException extends RuntimeException { }

try {
    ...
} catch (MyException e) {

}

Your exception extends from Throwable, so it is cheched exception. Since the compiler noticed that it is never thrown, so the compile fails.



来源:https://stackoverflow.com/questions/52041230/java-exception-as-checked-exception-but-not-required-to-be-thrown-in-trycatch

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!