简体   繁体   English

Java Exception as checked Exception但不需要在trycatch中抛出

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

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! 我知道Exception也在扩展Throwable,也是一个经过检查的异常,MyException也在扩展Throwable,这也是一个经过检查的异常!

My question is why Exception is not required to be thrown in the try catch but MyException is? 我的问题是为什么不需要在try catch中抛出异常,但MyException是? I think that both are checked exception so which is the difference?? 我认为两者都是检查异常所以哪个区别?

Sorry if the question is simple. 对不起,问题很简单。

It is explained in the Java Language Specification (emphasis in bold): 它在Java语言规范中进行了解释(以粗体强调):

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 . 如果catch子句可以捕获已检查的异常类E1并且不是对应于catch子句的try可以抛出作为E1的子类或超类的已检查异常类的情况,那么这是编译时错误, 除非E1是Exception或类的超类Exception

I guess the rationale behind this is that: MyException is indeed a checked exception. 我想这背后的基本原理是: MyException确实是一个经过检查的异常。 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. 但是,未经检查的异常也会扩展ExceptionRuntimeException传递继承),因此从编译器执行的异常分析中排除包含Exception类的catch

Exception extends from RuntimeException will considered as uncheched exception, so it's ok: RuntimeException扩展的异常将被视为未经检查的异常,所以没关系:

class MyException extends RuntimeException { }

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

}

Your exception extends from Throwable , so it is cheched exception. 你的异常从Throwable扩展,所以它被解除异常。 Since the compiler noticed that it is never thrown, so the compile fails. 由于编译器注意到它从未被抛出,因此编译失败。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM