Java之异常处理

发布于:2024-05-10 ⋅ 阅读:(26) ⋅ 点赞:(0)

一、认识异常

1.异常的概念

Java 中,将程序执行过程中发生的不正常行为称为异常。。比如之前写代码时经常遇到的:
1. 算术异常
System.out.println(10 / 0);
// 执行结果
Exception in thread "main" java.lang.ArithmeticException: / by zero
2. 数组越界异常
int[] arr = {1, 2, 3};
System.out.println(arr[100]);
// 执行结果
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 100
3. 空指针异常
int[] arr = null;
System.out.println(arr.length);
// 执行结果
Exception in thread "main" java.lang.NullPointerException
从上述过程中可以看 到,java中不同类型的异常,都有与其对应的类来进行描述。 

2.异常的体系结构

异常种类繁多,为了对不同异常或者错误进行很好的分类管理,Java内部维护了一个异常的体系结构:

从上图中可以看到:
1. Throwable 是异常体系的顶层类,其派生出两个重要的子类 , Error Exception
2. Error 指的是 Java 虚拟机无法解决的严重问题,比如: JVM 的内部错误、资源耗尽等 ,这种错误很少发生,典型代表: StackOverflowError(栈溢出) OutOfMemoryError(内存溢出) ,一旦发生回力乏术。
3. Exception 异常产生后程序员可以通过代码进行处理,使程序继续执行。我们平时所说的异常就是Exception。

3. 异常的分类

异常可能在编译时发生,也可能在程序运行时发生,根据发生的时机不同,可以将异常分为
1. 编译时异常
在程序编译期间发生的异常,称为编译时异常,也称为受检查异常
class Person implements Cloneable{
    public String name;

    public Person(String name) {
        this.name = name;
    }

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}
public static void main(String[] args)  {
        Person person1 = new Person("zhangsan");
        Person person2 = (Person)person1.clone();

    }
// 因为main方法没有使用throws CloneNotSupportedException,这个程序将不能运行,在编译时就会报错。后面会讲到throws
2. 运行时异常
在程序执行期间发生的异常,称为运行时异常,也称为非受检查异常
RunTimeException 以及其子类对应的异常,都称为运行时异常 。比如: NullPointerException
ArrayIndexOutOfBoundsException ArithmeticException
注意:编译时出现的语法性错误,不能称之为异常。例如将 System.out.println 拼写错了 , 写成了system.out.println. 此时编译过程中就会出错.

二、 异常的处理

1.异常的抛出

在自定义异常类中必须使用throw来抛出异常(后面讲到)。在Java中,可以借助throw关键字,抛出一个指定的异常对象,将错误信息告知给调用者。具体语法如下

throw new XXXException("异常产生的原因");

例题:实现一个获取数组中任意位置元素的方法。

public class App {
public static int getElement(int[] array, int index){
if(null == array){
throw new NullPointerException("传递的数组为null");
}
if(index < 0 || index >= array.length){
throw new ArrayIndexOutOfBoundsException("传递的数组下标越界");
}
return array[index];
}
public static void main(String[] args) {
int[] array = {1,2,3};
getElement(array, 3);
}
}
//输出结果
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 传递的数组下标越界
	at App.getElement(App.java:7)
	at App.main(App.java:13)
注意事项
1. throw 必须写在方法体内部
2. 抛出的对象必须是 Exception 或者 Exception 的子类对象
3. 如果抛出的是 RunTimeException 或者 RunTimeException 的子类,则可以不用处理,直接交给 JVM 来处理
4. 如果抛出的是编译时异常,用户必须处理,否则无法通过编译
5. 异常一旦抛出,其后的代码就不会执行

2.异常的声明

处在方法声明时参数列表之后,当方法中抛出编译时异常,用户不想处理该异常,此时就可以借助throws 将异常抛给方法的调用者(上级)来处理。即当前方法不处理异常,提醒方法的调用者(上级)处理异常
语法格式:
修饰符 返回值类型 方法名(参数列表) throws 异常类型1,异常类型2...{
}
注意事项
1. throws 必须跟在方法的参数列表之后
2. 声明的异常必须是 Exception 或者 Exception 的子类
3. 方法内部如果抛出了多个异常, throws 之后必须跟多个异常类型,之间用逗号隔开, 如果抛出多个异常类型具有父子关系,直接声明父类即可。
4. 调用声明抛出异常的方法时,调用者必须对该异常进行处理,或者继续使用 throws抛出,如果到 最高级 也没有捕获异常,将交给jvm 处理, 程序就会异常终止 ( 和我们最开始未使用 try  atch 时是一样的 )

3.异常的处理

throws 对异常并没有真正处理,而是将异常报告给抛出异常方法的调用者,由调用者处理。如果真正要对异常进行处理,就需要try-catch。
语法格式:
try{
// 将可能出现异常的代码放在这里
}catch(要捕获的异常类型 e){
// 如果try中的代码抛出异常了,此处catch捕获时异常类型与try中抛出的异常类型一致时,或者是try中抛出异常的基类
时,就会被捕获到
// 对异常就可以正常处理,处理完成后,跳出try-catch结构,继续执行后序代码
}[catch(异常类型 e){
// 对异常进行处理
}finally{
// 此处代码一定会被执行到
}]
// 后序代码
// 当异常被捕获到时,异常就被处理了,这里的后序代码一定会执行
// 如果捕获了,由于捕获时类型不对,那就没有捕获到,这里的代码就不会被执行
注意:
1. []中表示可选项,可以添加,也可以不用添加
2. try中的代码可能会抛出异常,也可能不会

例题:演示throws作用

class app {
    public static void main(String[] args) throws ArrayIndexOutOfBoundsException {
func();
    }
    public static void func(){
        try {

            int[] arr = {1, 2, 3};
            System.out.println(arr[100]);
        } catch (ArrayIndexOutOfBoundsException e) {
            e.printStackTrace();
        }
        System.out.println("after try catch");
    }
}

当然,上面代码可以省略throws(仅对运行时异常适用),在编译时异常中就不能省略了。

注意事项:
1. try块内抛出异常位置之后的代码将不会被执行
2. 如果抛出异常类型与catch时异常类型不匹配,即异常不会被成功捕获,也就不会被处理,继续往外抛,直到JVM收到后中断程序----异常是按照类型来捕获的

public static void main(String[] args) {
try {
int[] array = {1,2,3};
System.out.println(array[3]); // 此处会抛出数组越界异常
}catch (NullPointerException e){ // 捕获时候捕获的是空指针异常--真正的异常无法被捕获到
e.printStackTrace();
}
System.out.println("后序代码");
}
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at day20210917.ArrayOperator.main(ArrayOperator.java:24)
3. try 中可能会抛出多个不同的异常对象,则必须用多个 catch 来捕获 ---- 即多种异常,多次捕获
public static void main(String[] args) {
int[] arr = {1, 2, 3};
try {
System.out.println("before");
// arr = null;
System.out.println(arr[100]);
System.out.println("after");
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("这是个数组下标越界异常");
e.printStackTrace();
} catch (NullPointerException e) {
System.out.println("这是个空指针异常");
e.printStackTrace();
}
System.out.println("after try catch");
}
也可以写成这样:
catch (ArrayIndexOutOfBoundsException | NullPointerException e) {
...
}
如果异常之间具有父子关系,一定是子类异常在前 catch ,父类异常在后 catch ,否则语法错误:因为父类在前的话,后面子类这个代码没意义了,会报错
public static void main(String[] args) {
int[] arr = {1, 2, 3};
try {
System.out.println("before");
arr = null;
System.out.println(arr[100]);
System.out.println("after");
} catch (Exception e) { // Exception可以捕获到所有异常
e.printStackTrace();
}catch (NullPointerException e){ // 永远都捕获执行到
e.printStackTrace();
}
System.out.println("after try catch");
}
Error:(33, 10) java: 已捕获到异常错误java.lang.NullPointerException
4. 可以通过一个 catch 捕获所有的异常,即多个异常,一次捕获 ( 不推荐)
public static void main(String[] args) {
int[] arr = {1, 2, 3};
try {
System.out.println("before");
arr = null;
System.out.println(arr[100]);
System.out.println("after");
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("after try catch");
}
由于 Exception 类是所有异常类的父类 . 因此可以用这个类型表示捕捉所有异常。
备注: catch 进行类型匹配的时候, 不光会匹配相同类型的异常对象, 也会捕捉目标异常类型的子类对象.

4. finally

待更新~~~

三、自定义异常类