Java中的checked exception和unchecked exception

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.

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值