这篇文章只是学习过程中的知识点记录,不敢做深入的分析
异常简介
从上图,我们可以发现,JAVA的异常分为两类,Exception和Error,它们都继承自Throwable
Exception分为RuntimeException和一般异常
RuntimeException是运行时异常,也叫unchecked exception,RuntimeException不强制要求处理,(当然你自己要处理也可以)
一般异常是编译时异常,也叫checked exception,这种异常必须处理
常见的异常
编译时异常: 程序正确,但因为外在的环境条件不满足引发。例如:用户错误及I/O问题----程序试图打开一个并不存在的远程Socket端口。这不是程序本身的逻辑错误,而很可能是远程机器名字错误(用户拼写错误)。对商用软件系统,程序开发者必须考虑并处理这个问题。Java编译器强制要求处理这类异常,如果不捕获这类异常,程序将不能被编译。一般如果用Eclispe,输入代码后都会进行红色提示。
IOexception(文件I/O、网络I/O)、SQLException等属于这种情况
运行期异常: 这意味着程序存在bug,.这类异常需要更改程序来避免,Java编译器强制要求处理这类异常。
NullPointerException - 空指针引用异常
ArithmeticException - 算术运算异常
IndexOutOfBoundsException - 下标越界异常
NumberFormatException -数字格式异常
ClassCastException -类型强制转换异常
等都属于这一类
程序举例
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
/**
* Created by admin on 2017/5/23.
*/
public class test {
public static void main(String[] args) {
testRuntimeExecption();
testNotRuntimeException();
testException();
}
public static void testRuntimeExecption(){
//可以不用捕获
int[] a = {1,2,3};
//try {
for (int i = 0; i <= a.length; i++) {
System.out.println(a[i]);
}
//}catch (ArrayIndexOutOfBoundsException e){
//System.out.println("数组下标越界了");
//}
}
public static void testNotRuntimeException(){
//属于编译时异常
File file = new File("1.txt");
//unhandled exception
try {
FileReader fr = new FileReader(file);
}catch (FileNotFoundException e){
System.out.println("文件未找到");
}
}
public static void testException(){
try {
System.out.println(2/0);
}
catch(IndexOutOfBoundsException e){
System.out.println("发生了IndexOutOfBoundsException");
}
/*catch (ArithmeticException e){
System.out.println("发生了ArithmeticException");
}*/
catch (Exception e){
System.out.println("发生了异常");
}
finally {
System.out.println("finally一定会被运行");
}
}
}
通过第三个函数,可以发现继承的层次
public void run() throws InterruptedException{
Thread.sleep(1000);
System.out.println(Thread.currentThread().getName()+"正在执行");
}
这段程序的错误是,因为父类的run()没有抛出异常,所有重写的run()也不能抛出异常