码迷,mamicode.com
首页 > 编程语言 > 详细

Java中的checked exception和unchecked exception

时间:2015-08-09 18:53:46      阅读:147      评论:0      收藏:0      [点我收藏+]

标签:

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.

版权声明:本文为博主原创文章,未经博主允许不得转载。

Java中的checked exception和unchecked exception

标签:

原文地址:http://blog.csdn.net/u010999240/article/details/47378041

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!