Unchecked Exception 和 Checked Exception 比较

  Throwable 类是所有异常的始祖,它有两个直接子类 Error  /  Exception : 
  Error仅在Java虚拟机中发生动态连接失败或其它的定位失败的时候抛出一个Error对象。一般程序不用捕捉或抛出Error对象。 

Unchecked Exception:  
a. 指的是程序的瑕疵或逻辑错误,并且在运行时无法恢复。 
b. 包括Error与RuntimeException及其子类,如:OutOfMemoryError, UndeclaredThrowableException, IllegalArgumentException, IllegalMonitorStateException, NullPointerException, IllegalStateException, IndexOutOfBoundsException等。 
c. 语法上不需要声明抛出异常。 

Checked Exception:  
a. 代表程序不能直接控制的无效外界情况(如用户输入,数据库问题,网络异常,文件丢失等) 
b. 除了Error和RuntimeException及其子类之外,如:ClassNotFoundException, NamingException, ServletException, SQLException, IOException等。 
c. 需要try catch处理或throws声明抛出异常。 

有点困惑的是:RuntimeException (Unchecked)是Exception (Checked)的子类。 

示例: 
Java代码   收藏代码
  1. public class GenericException extends Exception {  
  2.     public GenericException() {  
  3.     }  
  4.   
  5.     public GenericException(String message) {  
  6.         super(message);  
  7.     }  
  8. }  


Java代码   收藏代码
  1. public class TestException {  
  2.     public void first() throws GenericException {  
  3.         throw new GenericException("Generic exception"); // Checked Exception需要显式声明抛出异常或者try catch处理  
  4.     }  
  5.       
  6.     public void second(String msg) {  
  7.         if (msg == null)  
  8.             throw new NullPointerException("Msg is null"); // Unchecked Exception语法上不需要处理  
  9.     }  
  10.       
  11.     public void third() throws GenericException {  
  12.         first(); // 调用有Checked Exception抛出的方法也需要try catch或声明抛出异常  
  13.     }  
  14.   
  15.     public static void main(String[] args) {  
  16.         TestException test = new TestException();  
  17.         try {  
  18.             test.first();  
  19.         } catch (GenericException e) {  
  20.             e.printStackTrace();  
  21.         }  
  22.           
  23.         test.second(null);  
  24.     }  
  25. }  
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值