java 受检查异常_Java受检异常和不受检异常

Java异常有checked exception(受检异常)和unchecked exception(不受检异常), 编译器在编译时,对于受检异常必须进行try...catch或throws处理,否则无法通过编译,不受检异常没有这个约束。

不受检异常包括RuntimeException及其子类 ,下图不受检异常未处理可以通过编译:

2bdf8747b74c8d405efadf1a37b13fc0.png

受检异常包括Exception及其子类但不包括RuntimeException及其子类,下面的示例代码受检异常无法编译:

package test;

import java.io.IOException;

public class ExceptionDemo {

public static void main(String[] args) {

//JDK定义的受检异常

//ioexception sqlexception filenotfoudexception 受检异常,必须对异常进行处理,否则无法编译

throw new Exception(); //无法编译

throw new IOException(""); //无法编译

//自定义受检异常

throw new CustomCheckedException();//无法编译

}

}

/**

* 自定义受检异常

*

*/

class CustomCheckedException extends 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.

概况起来就是,受检异常和不受检异常都是在程序运行时候,出现了错误。当调用者接受到不受检异常时,什么都做不了,比如NullPointerException除了打下日志,调用者无从下手了;当调用者接受到受检异常时,就知道哪里出了问题该如何处理了,比如接受导FileNotFoundException找不到文件时,调用者就可以换个目录继续找文件了。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值