Checked Exception与Runtime Exception 的区别
Java里有个很重要的特色是Exception ,也就是说允许程序产生例外状况。而在学Java 的时候,我们也只知道Exception
的写法,却未必真能了解不同种类的Exception 的区别。
首先,您应该知道的是Java 提供了两种Exception
的模式,一种是执行的时候所产生的Exception (Runtime Exception),另外一种则是受控制的Exception (Checked
Exception)。
所有的Checked Exception 均从java.lang.Exception 继承而来,而Runtime Exception 则继承java.lang.RuntimeException 或java.lang.Error (实际上java.lang.RuntimeException 的上一层也是java.lang.Exception)。
当我们撰写程序的时候,我们很可能会对选择某种形式的Exception 感到困扰,到底我应该选择Runtime Exception 还是Checked Exception ?
其实,在运作上,我们可以通过Class 的method如何产生某个Exception以及某个程序如何处理这个被产生来的Exception 来了解它们之间的差异。
首先我们定义一个自己的Exception
public class CException extends Exception {
public CException() {
}
public CException(String message) {
super(message);
}
}
然后我们撰写一个可能产生 CException 的 Class
public class TestException {
public void method1() throws CException {
throw new CException("Test Exception");
}
public void method2(String msg) {
if (msg == null) {
throw new NullPointerException("Message is null");
}
}
public void method3() throws CException {
method1();
}
// 以下省略
// ...
public static void main(String argv[]) {
TestException te = new TestException();
try {
te.method1();
} catch (CException ce) {
// ....
}
}
}
在这三个method 中,我们看到了method1 和method2 的程序码内都会产生Exception,但method3 的程序码中(大括号内),并没产生Exception,但在method3 的定义中,暗示了这个method 可能产生CException。虽然包含在try 与catch中,并不表示这段程序码一定会收到CException,但它的用意在于提醒呼叫者,执行这个method
可能产生的意外,而使用者也必须要能针对这个意外做出相对应的处理方式。
当使用者呼叫method2() 时,并不需要使用try 和catch 将程序码包起来,因为method2 的定义中,并没有throws 任何的Exception ,如:
public static void main(String argv[]) {
TestException te = new TestException();
// 不会产生 Exception
te.method2("Hello");
// 会产生 Exception
te.method2(null);
}
程序在执行的时候,也不见得会真的产生NullPointerException ,这种Exception叫做runtime exception 也有人称为unchecked exception ,产生Runtime Exception 的method (在这个范例中是method2) 并不需要在宣告method 的时候定义它将会产生哪一种Exception 。
在TestException的method3() 中,我们看到了另外一种状况,也就是method3里呼叫了method1() ,但却没有将method1 包在try 和catch之间。相反,在method3() 的定义中,它定义了CException,实际上就是如果method3 收到了CException,它将不处理这个CException ,而将它往外丢。当然,由于method3 的定义中有throws CException ,因此呼叫method3的程序码也需要有try catch 才行。
因此从程序的运作机制上看,Runtime Exception与Checked Exception不一样,然而从逻辑上看,Runtime Exception 与Checked Exception 在使用的目的上也不一样。一般而言,Checked Exception 表示这个Exception
必须要被处理,也就是说程序设计者应该已经知道可能会收到某个Exception(因为要try catch住) ,所以程序设计者应该能针对这些不同的Checked Exception 做出不同的处理。而Runtime Exception通常会暗示着程序上的错误,这种错误会导致程序设计者无法处理,而造成程序无法继续执行下去。
看看下面的例子:
String message[] = {"message1", "message2","message3"};
System.out.println(message[3]);
这段程序码在Compile时并没问题,但在执行时则会出现ArrayIndexOutOfBoundException的例外,在这种状况下,我们亦无法针对这个Runtime Exception 做出有意义的动作,这就像是我们呼叫了testException 中的method2 ,却引发了它的NullPointerException一样,在这种状况下,我们必须对程序码进行修改,从而避免这个问题。
因此,实际上我们应该也必须要去抓取所有的Checked Exception,同时最好能在这些Checked Exception 发生的时候做出相对应的处理,好让程序能面对不同的状况。
然而对于Runtime Exception ,有些人建议将它catch住,然后导向其它地方,让程序继续执行下去,这种作法并非不好,但它会让我们在某些测试工具下认为我们的程序码没有问题,因为我们将Runtime Exception"处理"掉了,事实却不然!譬如很多人的习惯是在程序的进入点后用个大大的try catch 包起来,如:
public class Runtest1 {
public static void main(String argv[]) {
try {
// ...
} catch (Exception e) {
}
}
}
在这种情况下,我们很可能会不知道发生了什么Exception 或是从哪一行发出的,因此在面对不同的Checked
Exception时,我们可已分别去try catch它。而在测试阶段时,如果碰到Runtime Exception,我们可以让它就这样发生,接着再去修改我们的程序码,让它避免Runtime Exception,否则,我们就应该仔细追究每一个Exception
,直到我们可以确定它不会有Runtime Exception 为止!
对于Checked Exception 与Runtime Exception ,我想应该有不少人会有不同的观点,无论如何,程序先要能执行,这些Exception 才有机会产生。因此,我们可以把这些Exception当成是Bug ,也可以当成是不同的状况(Checked Exception),或当成是帮助我们除错的工具(Runtime Exception),但前提是我们需要处理这些Exception ,如果不处理,那么问题或状况就会永远留在那里。
Checked Exception与Runtime Exception 的区别的更多相关文章
- Exception (2) Java Exception Handling
The Java programming language uses exceptions to handle errors and other exceptional events.An excep ...
- Java中Error和Exception的异同以及运行时异常(Runtime exception)与检查型异常(checked exception)的区别
一:Error和Exception的基本概念: 首先Exception和Error都是继承于Throwable 类,在 Java 中只有 Throwable 类型的实例才可以被抛出(throw)或者捕 ...
- java中的Checked Exception和Unchecked Exception的区别
Java 定义了两种异常: - Checked exception: 继承自 Exception 类是 checked exception.代码需要处理 API 抛出的 checked excepti ...
- Java常见异常(Runtime Exception )小结(转)
原文链接:Java常见异常(Runtime Exception )小结 Java异常体系结构呈树状,其层次结构图如图 1所示: 本文重在Java中异常机制的一些概念.写本文的目的在 ...
- final,finally,finalize有什么区别?String, StringBuffer, StringBuilder有什么区别?Exception和Error有什么区别?
继上篇JVM学习之后,后面将分三期深入介绍剩余JAVA基础面试题,每期3题. 题目一.final,finally,finalize有什么区别? /*请尊重作者劳动成果,转载请标明原文链接:*/ /* ...
- 《Java核心技术36讲》阅读笔记:Exception和Error有什么区别?
1.Exception 和 Error有什么区别?运行时异常与一般异常有什么区别? Exception和Error都继承自java.lang.Throwable.在Java中只有Throwable的实 ...
- Co-variant array conversion from x to y may cause run-time exception
http://stackoverflow.com/questions/8704332/co-variant-array-conversion-from-x-to-y-may-cause-run-tim ...
- Exception 和 Error 有什么区别么
声明 本篇所涉及的提问,正文的知识点,全都来自于杨晓峰的<Java核心技术36讲>,当然,我并不会全文照搬过来,毕竟这是付费的课程,应该会涉及到侵权之类的问题. 所以,本篇正文中的知识点, ...
- 请写出5种常见到的runtime exception。
请写出5种常见到的runtime exception. 解答: NullPointerException:当操作一个空引用时会出现此错误. NumberFormatException:数据格式转换出现 ...
随机推荐
- React-非dom属性-ref标签
<!DOCTYPE html> <html lang="zh-cn"> <head> <meta charset="UTF-8& ...
- CentOS防火墙操作实例(启动、停止、开、闭端口)
注:防火墙的基本操作命令: 查询防火墙状态: [root@localhost ~]# service iptables status<回车> 停止防火墙: [root@localh ...
- Mac显示和隐藏文件的命令
打开命令行输入即可,不过要重启Finder才能看到效果 显示: defaults write com.apple.finder AppleShowAllFiles -bool true 隐藏: def ...
- postgreSQLG关闭活动的connection、删除活动的数据库
First, find the activities that are taken place against the target database, you can query thepg_sta ...
- Allegro16.3约束设置
差分对的约束设置 第一步,差分对的设置 差分对的设置有很多方法,下面介绍两种最常用的方法. 1. 点击菜单Logic→Assign Differential Pair... 弹出以下对话框. 点击你想 ...
- 16.allegro元件手动摆放[原创]
一.手动摆放 --- -- 一个个摆放 二.全局设置 --- 这里都是全局的 显示信息 三.快速摆放所有元件 -- ---- 四.显示的内容很多,我们来设置下显示 -- 1 --- 2 --- 3 - ...
- find a filename from a filehandle in Perl
my $filename='/tmp/tmp.txt';open my $fh, '>', $filename;my $fd = fileno $fh;print readlink(" ...
- Linux 下安装python软件包(pip、nose、virtualenv、distribute )
新手刚开始学习Python,目前学习<笨方法学python>ing- 在学习习题46时需要安装几个软件包:pip.nose.virtualenv.distribute !在此记录Linux ...
- KEYUSE
typedef struct keyuse_t { TABLE *table; Item *val; /**< or value if no field */ table_map used_ta ...
- IOS学习-报错误 Finishing up a navigation transition in an unexpected state. Navigation Bar subview tree might get corrupted.
环境:XCODE:5.0.2 IOS7模拟器 界面:使用storyboard 拖拽 简单应用:一个CoreData的CRUD用例. 界面如下图(一个UITableViewController 列表 ...