Java Exception as checked Exception但不需要在trycatch中抛出 [英] Java Exception as checked Exception but not required to be thrown in trycatch
问题描述
我有这个片段。
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
我知道Exception正在扩展Throwable并且也是一个已检查的异常,MyException也在扩展Throwable,这也是一个已检查的异常!
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!
我的问题是为什么不需要在try catch中抛出Exception但MyException是什么?我认为这两个都是检查异常,这是差异?
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.
推荐答案
Java语言规范(以粗体强调):
这是一个编译时如果
catch
子句可以捕获已检查的异常类E1,则不会出现尝试$ c的情况对应于
catch
子句的$ c>块可以抛出一个已检查的异常类,它是E1的子类或超类,除非E1是异常
或超类异常
。
It is a compile-time error if a
catch
clause can catch checked exception class E1 and it is not the case that thetry
block corresponding to thecatch
clause can throw a checked exception class that is a subclass or superclass of E1, unless E1 isException
or a superclass ofException
.
我想这背后的基本原理是: MyException
确实是一个经过检查的例外。但是,未经检查的异常也会扩展异常
(来自 RuntimeException
的传递继承),因此拥有 catch
包括异常
类从编译器完成的异常分析中排除。
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.
这篇关于Java Exception as checked Exception但不需要在trycatch中抛出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!