异常处理:
首先看一段出现异常的代码:
public class ExcDemo {
public static void main(String[] args) {
int[] arr = new int[3];
System.out.println("------begin-----");
System.out.println(arr[4]);
System.out.println("------over------");
}
}
异常的处理方法:
方式一:将异常捕获:try-catch
try{
可能出现异常的语句
}catch(异常的类型 对象){
异常的处理方式
}finally{
出口—(finally块一定会被执行)
}
在上面的代码中,catch块可以出现多次,组合方式有以下几种
- try…catch
- try…finally
- try…catch…finally
异常处理:
public static void main(String[] args) {
int[] arr = new int[3];
System.out.println("------begin-----");
try{
System.out.println(arr[4]);
}catch (ArrayIndexOutOfBoundsException e){
System.out.println("异常处理");
}
System.out.println("------over------");
}
可以看到将异常捕获后,程序不会卡在出现异常的地方,会在异常处理后继续执行后面的代码
在catch块中可以调用异常类中的printStackTrace()方法打印错误堆栈信息
方式二: 将异常抛出
throw关键字: 用在方法内部,表示可以人为将异常抛出
public static void main(String[] args) {
int[] arr = new int[4];
System.out.println("------begin-----");
if (arr.length == 3){
System.out.println("是指定大小的数组");
}else {
throw new ArrayIndexOutOfBoundsException("数组长度错误");
}
System.out.println("------over------");
}
throws关键字: 用在方法声明处,表示调用此方法会产生异常,但是我并没有将异常处理,抛到上层进行处理
public class ExcDemo {
public static void main(String[] args) {
int[] arr = new int[1];
System.out.println(getvalue(arr));
}
public static int getvalue(int[] arr)throws ArrayIndexOutOfBoundsException{
if (arr.length == 0){
throw new NullPointerException("空数组");
}
return arr[3];
}
}
多catch块处理:
当抛出的多个异常之间有继承关系时,必须先捕获子类的异常,因为子类的异常类对象可通过天然的向上转型自动被父类所接受
总结:
- 运行时异常发生时,不建议使用异常捕获的方式进行异常处理,比如数组中的空指针异常,发生异常后后面的代码没有运行的必要,应该停止程序,修改代码
- 方法重写时,若父类的方法抛出异常。子类重写后的方法可以抛也可以不抛
- 父类方法不抛异常。子类重写后的方法不能抛异常