java中checked和unchecked 异常处理
有两种类型的异常:一种是checked异常一种是unchecked异常,在这篇文章中我们将利用实例来学习这两种异常,checked的异常和unchecked异常最大的区别就是checked去唱是在编译时检查的而unchecked异常是在运行时检查的。
什么是checked异常呢?
checked异常在编译时检查,这意味着如果一个方法抛出checked异常,那么它应该使用try-catch块或者使用throws关键字来处理这个异常,否则的话程序会报编译错误,命名为checked异常是因为是在编译时checked的。
用例子来理解这个问题,在这个例子中,我们读取myfile.txt这个文件并且将它的内容输出到屏幕上,在下边这个程序中有三处异常被抛出。FileInputStream使用了指定的文件路径和名称,抛出FileNotFoundException,这个读取文件内容的read()函数抛出IOException异常,关闭文件输入流的close()函数同样也抛出IOException异常。
- import java.io.*;
- class Example {
- public static void main(String args[])
- {
- FileInputStream fis = null;
- /*This constructor FileInputStream(File filename)
- * throws FileNotFoundException which is a checked
- * exception*/
- fis = new FileInputStream("B:/myfile.txt");
- int k;
- /*Method read() of FileInputStream class also throws
- * a checked exception: IOException*/
- while(( k = fis.read() ) != -1)
- {
- System.out.print((char)k);
- }
- /*The method close() closes the file input stream
- * It throws IOException*/
- fis.close();
- }
- }
输出的结果:
- Exception in thread "main" java.lang.Error: Unresolved compilation problems:
- Unhandled exception type FileNotFoundException
- Unhandled exception type IOException
- Unhandled exception type IOException
为什么这个会编译错误呢?像我在一开始提到的checked异常在编译时被检查,因为我们没有处理这些异常,我们的编译程序报出了编译错误。
怎么解决这个错误呢?有两种方式避免这种错误,我们一条一条的来看:
方法一:使用throws关键字声明异常
我们知道在main()函数里有三个checked异常发生,那么避免这种编译错误的一种方式就是:在方法上使用throws关键字声明一个异常,你或许会想我们的代码抛出FileNotFoundException和IOEXception,为什么我们是声明了一个IOException呢,原因是IOException是FileNotFoundException的父类,前者默认覆盖了后者,如果你想你也可以这样声明异常:
- public static void main(String args[]) throws IOException, FileNotFoundException.
- import java.io.*;
- class Example {
- public static void main(String args[]) throws IOException
- {
- FileInputStream fis = null;
- fis = new FileInputStream("B:/myfile.txt");
- int k;
- while(( k = fis.read() ) != -1)
- {
- System.out.print((char)k);
- }
- fis.close();
- }
- }
输出结果:
File content is displayed on the screen.
方法二:使用try-catch块处理异常
上一种方法并不是很好,那不是处理异常最好的方式,你应该对每一个异常给出有意义的信息,使那些想了解这些错误的人能够理解,下边是这样的代码:
- import java.io.*;
- class Example {
- public static void main(String args[])
- {
- FileInputStream fis = null;
- try{
- fis = new FileInputStream("B:/myfile.txt");
- }catch(FileNotFoundException fnfe){
- System.out.println("The specified file is not " +
- "present at the given path");
- }
- int k;
- try{
- while(( k = fis.read() ) != -1)
- {
- System.out.print((char)k);
- }
- fis.close();
- }catch(IOException ioe){
- System.out.println("I/O error occurred: "+ioe);
- }
- }
- }
上边的代码能够正常运行,并将内容显示出来
下边是一些其他的checked异常
SQLException
IOEXception
DataAccessException
ClassNotFoundException
InvocationTargetException
什么是unchecked异常呢
unchecked异常在编译时不会检查,这意味着即使你没有声明或者处理异常你的程序也会抛出一个unchecked异常,程序不会给出一个编译错误,大多数情况下这些异常的发生是由于用户在交互过程中提供的坏数据。这需要程序员提前去判断这种能够产生这种异常的情况并且恰当的处理它。所有的unchecked异常都是RuntimeException的子类。
我们来看一下下边的代码:
- class Example {
- public static void main(String args[])
- {
- int num1=10;
- int num2=0;
- /*Since I'm dividing an integer with 0
- * it should throw ArithmeticException*/
- int res=num1/num2;
- System.out.println(res);
- }
- }
如果你编译这段代码,这段代码将会被通过,但是当你运行的时候它将抛出ArithmeticException。这段代码清楚的表明了unchecked异常在编译期间是不会被checked的,他们在运行期间被检查,我们来看另一个例子:
- class Example {
- public static void main(String args[])
- {
- int arr[] ={1,2,3,4,5};
- /*My array has only 5 elements but
- * I'm trying to display the value of
- * 8th element. It should throw
- * ArrayIndexOutOfBoundsException*/
- System.out.println(arr[7]);
- }
- }
这段代码同样被成功的编译通过,因为ArrayIndexOutOfBoundsException是unchecked异常。
注意:这并不意味着编译器不检查这些异常我们就不处理这些异常了,事实上我们需要更加小心的处理这些异常,例如在上边的例子中,应该提供给用户一个他想读取的信息在数组中不存在的信息,以便用户修改这个问题
- class Example {
- public static void main(String args[])
- {
- try{
- int arr[] ={1,2,3,4,5};
- System.out.println(arr[7]);
- }catch(ArrayIndexOutOfBoundsException e){
- System.out.println("The specified index does not exist " +
- "in array. Please correct the error.");
- }
- }
- }
这里还有其他的一些常见的unchecked异常:
NullPointerException
ArrayIndexOutOfBoundsException
ArithmeticException
IllegalArgumentException
java中checked和unchecked 异常处理的更多相关文章
- java中checked异常和unchecked异常区别?
马克-to-win:checked和unchecked异常区别:结论就是:1)RuntimeException和他的子类都是unchecked异 常.其他的都是checked异常.马克-to-win: ...
- Java中@SuppressWarnings("unchecked")的作用
J2SE 提供的最后一个批注是 @SuppressWarnings.该批注的作用是给编译器一条指令,告诉它对被批注的代码元素内部的某些警告保持静默. 一点背景:J2SE 5.0 为 Java 语言增加 ...
- JAVA中的异常(异常处理流程、异常处理的缺陷)
异常处理流程 1)首先由try{...}catch(Exception e){ System.out.println(e); e.printStackTrace(); }finally{...}结构 ...
- 【Java】Checked、Unchecked Exception
Checked Exception:需要强制catch的异常, Unchecked Exception:这种异常时无法预料的,即RuntimeException,就是运行时的异常. Exception ...
- java中Thread的 interrupt异常处理
http://blog.csdn.net/srzhz/article/details/6804756
- java中异常的面试
https://blog.csdn.net/qq_36523638/article/details/79363652 1) Java中的检查型异常和非检查型异常有什么区别? 这又是一个非常流行的Jav ...
- 夯实Java基础系列10:深入理解Java中的异常体系
目录 为什么要使用异常 异常基本定义 异常体系 初识异常 异常和错误 异常的处理方式 "不负责任"的throws 纠结的finally throw : JRE也使用的关键字 异常调 ...
- Java中的Checked Exception——美丽世界中潜藏的恶魔?
在使用Java编写应用的时候,我们常常需要通过第三方类库来帮助我们完成所需要的功能.有时候这些类库所提供的很多API都通过throws声明了它们所可能抛出的异常.但是在查看这些API的文档时,我们却没 ...
- [Java] java中的异常处理
Java中的异常类都继承自Throwable类.一个Throwable类的对象都可以抛出(throw). Throwable对象可以分为两组.一组是unchecked异常,异常处理机制往往不用于这组异 ...
随机推荐
- qt 中文乱码
首先呢,声明一下,QString 是不存在中文支持问题的,很多人遇到问题,并不是本身 QString 的问题,而是没有将自己希望的字符串正确赋给QString. 很简单的问题,"我是中文&q ...
- 【Oracle学习笔记-2】Oracle基础术语解析
来自为知笔记(Wiz) 附件列表 Oracle概念解析.png 表空间.png 大小关系.png 段segment.png 块block.png 区entent.png 数据库基本概念.png
- Qt 资源文件
以下演示如何在Qt Creator使用QIcon加载一张 png 图片: 在工程上点右键,选择“添加新文件…”,在 Qt 分类下选择“Qt 资源文件”: 点击“选择…”按钮,打开“新建 Qt 资源文件 ...
- java操作Excel之POI(3)
一.字体处理 /** * 字体处理 */ public static void main(String[] args) throws Exception { Workbook wb = new HSS ...
- JavaScript之图片操作4
本次要实现的效果是,在一个盒子里面有一张长图,只显示了一部分,为方便用户浏览,当鼠标移入时,图片开始滚动,将盒子分成上下两部分,当鼠标移入上部分时,图片向上滚动,当鼠标移入下部分时,图片向下滚动. 为 ...
- RegExp实例
ECMAScript通过RegExp类型来支持正则表达式,常见的正则表达式为:var expression = /pattern / flags;其中的模式(pattern)部分可以使任何简单或复杂的 ...
- eclipse JDK 下载 and 安装 and 环境配置
eclipse和JDK软件下载 链接:https://pan.baidu.com/s/1bpRHVIhNtK9_FMVbi34YUQ 密码:y3xr eclipse和JDK这两个软件是配套使用的,适用 ...
- 杂项:GitHub
ylbtech-杂项:GitHub gitHub是一个面向开源及私有软件项目的托管平台,因为只支持git 作为唯一的版本库格式进行托管,故名gitHub. gitHub于2008年4月10日正式上线, ...
- [UE4]C++ string的用法和例子
使用场合: string是C++标准库的一个重要的部分,主要用于字符串处理.可以使用输入输出流方式直接进行操作,也可以通过文件等手段进行操作.同时C++的算法库对string也有着很好的支持,而且st ...
- mac 安装 nginx
我是用root用户装的 1.先安装PCRE库 可以在这里下载最新版,我这里使用的是8.33的版本然后在终端执行下面的命令. cd ~/Download tar xvzf pcre-8.33.tar.g ...