一、不处理异常
int[] arr = new int[] {1,2,3,4,5};
System.out.println("good");
System.out.println(arr[100]);
System.out.println("morning");
执行结果:
good
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 100
从以上的代码我们可以了解到,一旦发生了异常,程序就终止运行了;所以在上面的代码中“morning”没有被打印出来。
二、使用try catch执行上述代码
public static void main(String[] args) {
int[] arr = new int[] {1,2,3,4,5};
try {
System.out.println("good");
System.out.println(arr[100]);
System.out.println("morning");
} catch (ArrayIndexOutOfBoundsException e) {
//打印出现异常的调用栈
e.printStackTrace();
}
System.out.println("after try catch");
}
执行结果:
good
java.lang.ArrayIndexOutOfBoundsException: 100
after try catch
从上面代码的运行结果可以知道:一旦try中的代码出现了异常,那么try代码块中的程序就不会继续执行,而是转交到catch来执行,当catch执行完之后,再接着执行下面的代码。
三、catch只能处理对应种类的异常
依旧对于上面的代码,我们将异常类型改变后执行代码
public static void main(String[] args) {
int[] arr = new int[] {1,2,3,4,5};
try {
System.out.println("good");
System.out.println(arr[100]);
System.out.println("morning");
} catch (NullPointerException e) {
//打印出现异常的调用栈
e.printStackTrace();
}
System.out.println("after try catch");
}
执行结果:
good
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 100
at package1516.Test2.main(Test2.java:8)
可看出catch不能捕获到数组下标越界异常,因为异常的类型不匹配
四、catch可以有多个
一段代码可能会抛出不同的异常,而不同的异常对应着不同的处理方式,因此catch代码块可以有多个;
public static void main(String[] args) {
int[] arr = new int[] {1,2,3,4,5};
try {
System.out.println("good");
arr = null;
System.out.println(arr[100]);
System.out.println("morning");
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("数组下标越界异常");
e.printStackTrace();
} catch (NullPointerException e) {
System.out.println("空指针异常");
e.printStackTrace();
}
System.out.println("after try catch");
}
执行结果:
good
java.lang.NullPointerException
空指针异常
at package1516.Test2.main(Test2.java:9)
after try catch
因为Exception类是所有异常类的父类,所以可以用这个类型表示捕获所有的异常。
五、finally表示做最后的善后工作,其里面的代码是一定会被执行到的。
public static void main(String[] args) {
int[] arr = new int[] {1,2,3,4,5};
try {
System.out.println("good");
System.out.println(arr[100]);
System.out.println("night");
} catch (NullPointerException e) {
//打印出现异常的调用栈
e.printStackTrace();
} finally {
System.out.println("Good Good Good");
}
}
执行结果:
good
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 100
Good Good Good
at package1516.Test2.main(Test2.java:8)