Java Exception 和 Error 的区别

本文详细解析了Java中的Exception和Error的概念、区别、分类以及应用实例,深入理解异常处理机制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

从类的继承结构上看,Exception 和 Error 都继承与 java.lang.Throwable。

 

对于 Error ,API 的解释为:

 

 

An Error is a subclass of Throwable that indicates serious problems that a reasonable application should not try to catch. Most such errors are abnormal conditions. The ThreadDeath error, though a "normal" condition, is also a subclass of Error because most applications should not try to catch it.

A method is not required to declare in its throws clause any subclasses of Error that might be thrown during the execution of the method but not caught, since these errors are abnormal conditions that should never occur. That is, Error and its subclasses are regarded as unchecked exceptions for the purposes of compile-time checking of exceptions.

 

对于 Exception,API 的解释为:

 

 

he class Exception and its subclasses are a form of Throwable that indicates conditions that a reasonable application might want to catch.

The class Exception and any subclasses that are not also subclasses of RuntimeException are checked exceptions. Checked exceptions need to be declared in a method or constructor's throws clause if they can be thrown by the execution of the method or constructor and propagate outside the method or constructor boundary.

 

在对 Exception 的解释中,可以看到 Exception 分为两类,一类是 checked Exception,即除 RuntimeException 及其子类之外的所有 Exception,常见的有 IOException,SQLException;另一类是 unchecked Exception,即 RuntimeException,常见的有 NullPointerException,ArithmeticException。

 

checkedException 是需要在代码中显示地声明或者捕捉,而 uncheckedException 则不需要。至于原因,在 SCJP 的学习指导中有较好的阐述。

 

在 SCJP 1.6 的学习指导中,对 java 的Exception 和 Error 作如下的划分:

 

 

JVM exceptions Those exceptions or errors that are either exclusively or most logically thrown by the JVM.

 

Programmatic exceptions Those exceptions that are thrown explicitly by application and/or API programmers.

 

 

对于 JVM exceptions,编译器无法在程序运行前发现可能导致这类异常产生的问题。对于 RuntimeException,有一个很好的例子:

 

static String str ;

 

public static void main(String[] args) {

System.out.println(str.length());

}

 

虽然这段代码明显不合理,但却可以编译通过。对 str 调用 length 方法时,将产生 NullPointerException。而对于 Error ,也有一个简单的例子:

 

public class Bunnies {

 

 

void go(){

go();

}

 

public static void main(String[] args) {

new Bunnies().go();

}

}

 

运行之后,JVM 将产生 java.lang.StackOverflowError 。

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值