Java的Exception类是否为检查类型? [英] Is Java's Exception class a checked type?

查看:39
本文介绍了Java的Exception类是否为检查类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个显示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.

但是,由于在

如果catch子句捕获了已检查的异常类型E1,但是不存在已检查的异常类型E2,则以下所有条件均成立,这是编译时错误:

It is a compile-time error if a catch clause catches checked exception type E1 but there exists no checked exception type E2 such that all of the following hold:

  • E2< ;: E1
  • 与catch子句相对应的try块可以抛出E2
  • 立即封闭的try语句的前面的catch块没有捕获E2或E2的超类型.

除非E1是Exception类.

unless E1 is the class Exception.

其原因是 RuntimeException ,它是 Exception 的未经检查的异常子类.因此,与所有其他已检查的异常不同, catch(Exception)可能捕获未检查的异常,可以将其视为(在简化模型中) any 可能引发的异常. try 块.基本上 RuntimeException 与异常层次结构:(

The reason for this is RuntimeException, which is an unchecked exception subclass of Exception. So unlike all other checked exceptions, it's possible for catch (Exception) to catch an unchecked exception, which can be viewed (in a simplified model) as being potentially thrown by any try block. Basically RuntimeException messes with the exception hierarchy :(

这篇关于Java的Exception类是否为检查类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆