标签:
Java中有两种异常:checked exception和unchecked 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, 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