异常层次结构图
一、java异常体系
Thorwable类(表示可抛出)是所有异常和错误的超类,两个直接子类为Error和Exception,分别表示错误和异常。
其中异常类Exception又分为运行时异常(RuntimeException)和非运行时异常, 这两种异常有很大的区别,也称之为不检查异常(Unchecked Exception)和检查异常(Checked Exception)
1、Error与Exception
Error是程序无法处理的错误,它是由JVM产生和抛出的,比如OutOfMemoryError(内存溢出)、ThreadDeath等。这些异常发生时,Java虚拟机(JVM)一般会选择线程终止。
Exception是程序本身可以处理的异常,这种异常分两大类运行时异常和非运行时异常。程序中应当尽可能去处理这些异常。
2、运行时异常和非运行时异常
运行时异常都是RuntimeException类及其子类异常,如NullPointerException(空指针)、IndexOutOfBoundsException(数组越界)等,这些异常是不检查异常,程序中可以选择捕获处理,也可以不处理。这些异常一般是由程序逻辑错误引起的,程序应该从逻辑角度尽可能避免这类异常的发生。
非运行时异常是RuntimeException以外的异常,类型上都属于Exception类及其子类。从程序语法角度讲是必须进行处理的异常,如果不处理,程序就不能编译通过(报错不处理,一定不能编译)。如IOException、SQLException等以及用户自定义的Exception异常,一般情况下不自定义检查异常。
建一个exception的包,在里面建一个类Demo。
public class Demo {
public static void main(String[] args)
int a[] = new int[3];
for(int i=0;i<a.length;i++) { // 0 1 2
a[i] = i;//给a赋上初始值
}
}
不会报错且。
public class Demo {
public static void main(String[] args)
int a[] = new int[3];
System.out.println(Arrays.toString(a));
}
输出,不是空数组,任何类型的数组都有默认值,
public class Demo {
public static void main(String[] args)
int a[] = new int[3];
for(int i=0;i<a.length;i++) { // 0 1 2
a[i] = i;//给a赋上初始值
}
System.out.println(Arrays.toString(a));
}
输出[null, null, null]
将a.length 换成 10,运行,会出现数组越界,数组总共就三个数,出现第四个数,越界。运行时
异常。
所以用一种机制,try catch,即catch(捕获) 设置一个类型Exception e,
public class Demo {
public static void main(String[] args)
int a[] = new int[3];
try {
for(int i=0;i<10;i++) {
a[i] = i;
}
}catch(Exception e){
}
System.out.println("============");
}
先执行看一下,为============,然后在catch(捕获)里打印一下
public class Demo {
public static void main(String[] args)
int a[] = new int[3];
try {
for(int i=0;i<10;i++) {
a[i] = i;
}
}catch(Exception e){
System.out.println(e.getMessage());
}
System.out.println("============");
}
输出,之后再改成e
输出,告诉从哪里开始越界,从3开始溢出,
保护机制,让程序更加健壮。
也可以这样打印(更严格,指出错的位置),
不影响整个代码运行,专门的打印方法。