Java的Exception类是否为检查类型? [英] Is Java's Exception class a checked type?
问题描述
这是一个显示Java'Exception'类的相反行为的示例.
Here is an example that shows contrary behavior of Java 'Exception' class.
try {
}
catch(Exception ex) {
}
在检查类型为异常的情况下,如果我们在try块中保留一个catch块而对该特定检查异常没有任何引起错误的语句,则编译器将引发错误,例如永远不会从try语句主体中抛出此异常".但是在上述情况下,编译器不会给出任何错误.
In case of checked type of exception, if we keep a catch block without any error provoking statement to that particular checked exception in try block then, compiler will raise an error like "This exception is never thrown from the try statement body". But in above case compiler will not give any error.
另一方面,如果我们通过使用抛出关键字引发类型为'Exception'的异常,则该异常不会自动回避给调用者,如下所示:
On the other hand, if we raise an exception of type 'Exception' class by using throw key word, the exception will not be automatically ducked to a caller, like below:
throw new Exception();
在上述情况下,编译器会给出类似"未处理的异常类型Exception
"的错误.
In above case compiler gives error like "Unhandled exception type Exception
".
那么Java的Exception类是已检查还是未检查类型?
So is Java's Exception class a checked or unchecked type?
推荐答案
Exception
是已检查的异常.摘自JLS的第11.2节:>
Exception
is a checked exception. From section 11.2 of the JLS:
未经检查的异常类是RuntimeException类及其子类,而Error类及其子类.所有其他异常类都是已检查的异常类.
The unchecked exceptions classes are the class RuntimeException and its subclasses, and the class Error and its subclasses. All other exception classes are checked exception classes.