您的位置:首页 > 编程语言 > Java开发

Java中的checked exception和unchecked exception

2015-08-09 17:46 513 查看

Java中的checked exception和unchecked exception

Java中有两种异常:checked exception和unchecked exception。

checked exception

checked exception是这样定义:

A checked exception is an exception that must be either caught or declared in a method where it can be thrown.

也就是说,我们在编写代码时必须要捕获或者抛出的异常,它在编译时期就会被发现,强制要求做相应的处理,Checked exceptions子类是继承 java.lang.Exception,像FileNotFoundException,ParseException等都是checked exception,必须要使用try…catch(或者throws)来捕获异常。

unchecked exception

unchecked exception是这样定义的;

Unchecked, uncaught or runtime exceptions are exceptions that are not required to be caught or declared, even if it is allowed to do so.

unchecked exception继承自RuntimeException或Error ,unchecked exception指的是本该一切正常的程序发生了不该发生的异常,比如ArrayIndexOutOfBoundException, ClassCastException,NullPointerException,程序不该去catch这类异常,这类异常一般来说是代码有问题,需要修复。

那么我们什么时候选择checked exception,什么时候选择unchecked exception呢?官方文档给出了以下规则:

Here’s the bottom line guideline: If a client can reasonably be expected to recover from an exception, make it a checked exception. If a client cannot do anything to recover from the exception, make it an unchecked exception.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: