Java学习之Exception类中的checked异常和unchecked异常
1.Exception分类
如果需要弄明白Exception类中的checked异常和unchecked异常,我们首先需要了解Exception分类,Exception分类具体如下图所示:
2.checked异常和unchecked异常的定义
派生于Error或者RuntimeException的异常称为unchecked异常,所有其他的异常成为checked异常。
3.举例分析:
- unchecked异常
NullPointerException示例(main方法签名后可省去throws声明)
public class TestArray {
private static int[] x;
public static void main(String[] args){
System.out.println(x[0]);
}
}
//该程序会出现一下提示信息:
//Exception in thread "main" java.lang.NullPointerException
//at TestArray.main(TestArray.java:4)
常见的unchecked异常:
- NullPointerException
- ArrayIndexOutOfBoundsException
- ArithmeticException
- IllegalArgumentException
- checke异常
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.
常见的checked异常:
- SQLException
- IOEXception
- DataAccessException
- ClassNotFoundException
- InvocationTargetException