Java受检异常和不受检异常

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

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

受检异常包括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找不到文件时,调用者就可以换个目录继续找文件了。

 

posted on 2017-05-03 20:16  风之阡陌  阅读(5381)  评论(0编辑  收藏  举报

导航