zoukankan      html  css  js  c++  java
  • 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找不到文件时,调用者就可以换个目录继续找文件了。

  • 相关阅读:
    算法初步-插入排序
    [数据结构]之栈
    [数据结构]之队列
    [数据结构]之链表
    [数据结构]之顺序表
    SDL一环境配置
    三大框架结构的原理及其优点
    hibernate----hibernate的基础设置
    其他
    struts----用Action的属性接收参数
  • 原文地址:https://www.cnblogs.com/fzqm/p/6803680.html
Copyright © 2011-2022 走看看