Java中的checked exception和unchecked exception
2015-08-09 17:46
513 查看
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.
相关文章推荐
- spring总结
- springmvc学习第一天
- Java内部类的使用小结
- 使用javamail发送邮件
- 智渔课堂官方免费教程二:Java简介和开发环境配置
- I学霸官方免费教程二:Java简介和开发环境配置
- jdbc----java提供的访问数据库的接口【三】
- java_web学习(16)Ajax
- Java转换流2
- java 实现线程同步的方式有哪些
- Spring MVC 直接返还HTML视图
- Java反射机制之方法反射的基本操作
- java笔记--关于线程同步(5种同步方式)
- java synchronized静态同步方法与非静态同步方法,同步语句块
- java单链表常用操作
- java单链表常用操作
- 类的锁
- Myeclipse8.6 快速搭建ssh(JPA)开发环境 并自动生成dao ,model
- Java之旅(3)——EJB(初始)
- java.lang包下Number的简介