`
RyanXL
  • 浏览: 89922 次
文章分类
社区版块
存档分类

Java Exception 和 Error 的区别

 
阅读更多

从类的继承结构上看,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 。

 

 

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics