认识 异常

一、异常的概念与体系结构

1.1 异常的概念

在Java中,将程序执行过程中发生的不正常行为称为异常,如

1.算数异常

System.out.println(10/0);//ArithmeticException

2.数组越界异常

int[] array = new int[]{1,2,3,4,5};
System.out.println(array[10]);//ArrayIndexOutOfBoundsException

3.空指针异常

int[] array = null;
System.out.println(array[0]);//NullPointerException
System.out.println(array.length);//NullPointerException

1.2 异常的体系结构

1. Throwable:是异常体系的顶层类,其派生出两个重要的子类, Error 和 Exception

2. Error:指的是Java虚拟机无法解决的严重问题,比如:JVM的内部错误、资源耗尽等,典型代表: StackOverflowError和OutOfMemoryError,一旦发生回力乏术。

3. Exception:异常产生后程序员可以通过代码进行处理,使程序继续执行。

1.3 异常的分类

1. 编译时异常/受查异常

在程序编译期间发生的异常

class Person implements Cloneable{
    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}
public class Test {
    public static void main(String[] args) {
        Person person = new Person();
        Person person1 = (Person) person.clone();//必须对其进行捕获或声明以便抛出
    }
}

2.运行时异常/非受查异常

在程序执行期间发生的异常,RunTimeException以及其子类对应的异常,都称为运行时异常。

注意:编译时出现的语法性错误,不能称之为异常,这是 "编译期" 出错。而运行时指的是程序已经编译通过得到class 文件了, 再由 JVM 执行过程中出现的错误。

二、异常的处理

2.1 防御式编程

1. LBYL: Look Before You Leap. 在操作之前就做充分的检查. 即:事前防御型

 public class Test {
     public static void testException(int a) {
        if(a == 0) {
            throw new ArithmeticException("a == 0");
            //System.out.println("aadafv");//异常后面不能再加
        }
    }
    public static void main(String[] args) {
        testException(0);
    }
}

缺陷:正常流程和错误处理流程代码混在一起, 代码整体显的比较混乱。

2. EAFP: It's Easier to Ask Forgiveness than Permission. "事后获取原谅比事前获取许可更容易". 也就是先操 作, 遇到问题再处理. 即:事后认错型

public class Test {
    public static void function(int a) throws ArithmeticException {
        if(a == 0) {
            throw new ArithmeticException("a == 0");
        }
    }
    public static void main(String[] args) {
        try {
            function(0);
            System.out.println("下一条");
        }catch (ArithmeticException e) {
            System.out.println("捕获了异常,处理异常");
        }
        System.out.println("程序继续正常执行");
    }
}
运行结果

在Java中,异常处理主要的5个关键字:throw、try、catch、final、throws

2.2 异常的抛出--throw抛出

在Java中,可以借助throw关键字,抛出一个指定的异常对象,将错误信息告知给调用者。具体语法如下:

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

public class Test {
    public static void fuc(int[] array,int index) {
        if(array == null) {
            throw new NullPointerException("数组为null");
        }
        if (index < 0 || index >= array.length) {
            throw new ArrayIndexOutOfBoundsException("数组下标越界");
        }
    }
    public static void main(String[] args) {
        int[] array = {1,2,3};
        fuc(array,3);
    }
}

【注意事项】

1. throw必须写在方法体内部

2. 抛出的对象必须是Exception 或者 Exception 的子类对象

3. 如果抛出的是 RunTimeException 或者 RunTimeException 的子类,则可以不用处理,直接交给JVM来处理

4. 如果抛出的是编译时异常,用户必须处理,否则无法通过编译

5. 异常一旦抛出,其后的代码就不会执行

2.3 异常的捕获--throws声明 try-catch捕获

异常的捕获,也就是异常的具体处理方式,主要有两种:异常声明throws 以及 try-catch捕获处理。

2.3.1 throw声明异常

语法格式: 修饰符 返回值类型 方法名(参数列表) throws 异常类型1,异常类型2...{

}

public static void function(int a) throws ArithmeticException {
        if(a == 0) {
            throw new ArithmeticException("a == 0");
        }
    }

【注意事项】

1. throws必须跟在方法的参数列表之后

2. 声明的异常必须是 Exception 或者 Exception 的子类

3. 方法内部如果抛出了多个异常,throws之后必须跟多个异常类型,之间用逗号隔开,如果抛出多个异常类型 具有父子关系,直接声明父类即可。

4. 调用声明抛出异常的方法时,调用者必须对该异常进行处理,或者继续使用throws抛出

将光标放在抛出异常方法上,alt + Insert 快速 处理

2.3.2 try-catch捕获异常

throws对异常并没有真正处理,而是将异常报告给抛出异常方法的调用者,由调用者处理。如果真正要对异常进行处理,就需要try-catch。

语法格式: try{

        // 将可能出现异常的代码放在这里

}catch(要捕获的异常类型 e){

        // 如果try中的代码抛出异常了,此处catch捕获时异常类型与try中抛出的异常类型一致时,或者是try中抛出异常的基类 时,就会被捕获到

        // 对异常就可以正常处理,处理完成后,跳出try-catch结构,继续执行后序代码

}[catch(异常类型 e){

        // 对异常进行处理

}finally{

        // 此处代码一定会被执行到

}]

// 后序代码

// 当异常被捕获到时,异常就被处理了,这里的后序代码一定会执行

// 如果捕获了,由于捕获时类型不对,那就没有捕获到,这里的代码就不会被执行

注意:

1. []中表示可选项,可以添加,也可以不用添加

2. try中的代码可能会抛出异常,也可能不会

关于异常的处理方式

异常的种类有很多, 我们要根据不同的业务场景来决定.

对于比较严重的问题(例如和算钱相关的场景), 应该让程序直接崩溃, 防止造成更严重的后果

对于不太严重的问题(大多数场景), 可以记录错误日志, 并通过监控报警程序及时通知程序猿

对于可能会恢复的问题(和网络相关的场景), 可以尝试进行重试.

在我们当前的代码中采取的是经过简化的第二种方式. 我们记录的错误日志是出现异常的方法调用信息, 能很 快速的让我们找到出现异常的位置. 以后在实际工作中我们会采取更完备的方式来记录异常信息.

【注意事项】

1. try块内抛出异常位置之后的代码将不会被执行

2. 如果抛出异常类型与catch时异常类型不匹配,即异常不会被成功捕获,也就不会被处理,继续往外抛,直到 JVM收到后中断程序----异常是按照类型来捕获的

public static void main(String[] args) {
        int[] array = {1,2,3};
        try {
            array = null;
            System.out.println(array.length);
        }catch (ArithmeticException e) {
            System.out.println("处理ArrayIndexOutOfBoundsException异常");
        }finally {
            System.out.println("无论是否有异常都会执行");
        }
        System.out.println("继续执行");
    }

3. try中可能会抛出多个不同的异常对象,则必须用多个catch来捕获----即多种异常,多次捕获

public class Test {
    public static void main(String[] args) {
        int[] array = {1,2,3};
        try {
            System.out.println(array[10]);
            array = null;
            System.out.println(array.length);
        }catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("处理ArrayIndexOutOfBoundsException异常");
            e.printStackTrace();//将错误信息全部打印至控制台上展示
        }catch (NullPointerException e) {
            System.out.println("处理NullPointerException异常");
            e.printStackTrace();//将错误信息全部打印至控制台上展示
        }
    }
}

如果多个异常的处理方式是完全相同, 也可以写成这样:

 public static void main(String[] args) {
        int[] array = {1,2,3};
        try {
            array = null;
            System.out.println(array.length);
            System.out.println(array[10]);
        }catch (NullPointerException |ArrayIndexOutOfBoundsException e) {
            System.out.println("处理NullPointerException |ArrayIndexOutOfBoundsException异常");
        }finally {
            System.out.println("无论是否有异常都会执行");
        }
        System.out.println("继续执行");
    }

4. 可以通过一个catch捕获所有的异常,即多个异常,一次捕获(不推荐)

public static void main(String[] args) {
        int[] array = {1,2,3};
        try {
            array = null;
            System.out.println(array.length);
            System.out.println(array[10]);
        }catch (Exception e) {
            System.out.println("处理Exception异常");
        }finally {
            System.out.println("无论是否有异常都会执行");
        }
        System.out.println("继续执行");
    }

由于 Exception 类是所有异常类的父类. 因此可以用这个类型表示捕捉所有异常.

备注: catch 进行类型匹配的时候, 不光会匹配相同类型的异常对象, 也会捕捉目标异常类型的子类对象. 如刚才的代码, NullPointerException 和 ArrayIndexOutOfBoundsException 都是 Exception 的子类, 因此都能被捕获到.

2.3.3 finally

在写程序时,有些特定的代码,不论程序是否发生异常,都需要执行,比如程序中打开的资源:网络连接、数据库连接、IO流等,在程序正常或者异常退出时,必须要对资源进进行回收。另外,因为异常会引发程序的跳转,可能导致有些语句执行不到,finally就是用来解决这个问题的。

语法格式: try{

        // 可能会发生异常的代码

}catch(异常类型 e){

        // 对捕获到的异常进行处理

}finally{

        // 此处的语句无论是否发生异常,都会被执行到

}

// 如果没有抛出异常,或者异常被捕获处理了,这里的代码也会执行

public static void main(String[] args) {
    try{
        int[] arr = {1,2,3};
        arr[100] = 10;
        arr[0] = 10;
    }catch (ArrayIndexOutOfBoundsException e){
        System.out.println(e);
    }finally {
        System.out.println("finally中的代码一定会执行");
    }
    System.out.println("如果没有抛出异常,或者异常被处理了,try-catch后的代码也会执行");
}

问题:既然 finally 和 try-catch-finally 后的代码都会执行,那为什么还要有finally呢?

需求:实现getData方法,内部输入一个整形数字,然后将该数字返回,并再main方法中打印

 public static int getData() {
        Scanner scanner = null;
        try {
            scanner = new Scanner(System.in);
            int data = scanner.nextInt();
            return data;
        }catch (NullPointerException e) {
            e.printStackTrace();
        }finally {
            System.out.println("finally中代码");
        }
        if(scanner != null) {
            scanner.close();
        }
        return 0;
    }
    public static void main(String[] args) {
        int data = getData();
        System.out.println(data);
    }

上述程序,如果正常输入,成功接收输入后程序就返回了,try-catch-finally之后的代码根本就没有执行,即输入流 就没有被释放,造成资源泄漏。

注意:finally中的代码一定会执行的,一般在finally中进行一些资源清理的扫尾工作。

下面这段代码的结果是什么呢?

public static int testFuc() {
        try {
            return 10;
        }finally {
            return 20;
        }
    }
    public static void main(String[] args) {
        System.out.println(testFuc());
    }

finally 执行的时机是在方法返回之前(try 或者 catch 中如果有 return 会在这个 return 之前执行 finally). 但是如果 finally 中也存在 return 语句, 那么就会执行 finally 中的 return, 从而不会执行到 try 中原有的 return。故上述代码的结果为20。

一般我们不建议在 finally 中写 return (被编译器当做一个警告).

2.4 异常的处理流程

关于 "调用栈"

方法之间是存在相互调用关系的, 这种调用关系我们可以用 "调用栈" 来描述. 在 JVM 中有一块内存空间称为 "虚拟机栈" 专门存储方法之间的调用关系. 当代码中出现异常的时候, 我们就可以使用 e.printStackTrace(); 的方式查看出现异常代码的调用栈.

如果本方法中没有合适的处理异常的方式, 就会沿着调用栈向上传递

 public static void fuc2() {
        int[] arr = {1,2,3};
        System.out.println(arr[20]);
    }
    public static void main(String[] args) {
        try {
            fuc2();
            System.out.println("try中最后一条语句");
        }catch (ArrayIndexOutOfBoundsException e) {
            e.printStackTrace();
        }
        System.out.println("try-catch后语句");
    }

如果向上一直传递都没有合适的方法处理异常, 最终就会交给 JVM 处理, 程序就会异常终止(和我们最开始未使用 try catch 时是一样的)

 public static void fuc22() {
        int[] arr = {1,2,3};
        System.out.println(arr[20]);
    }
    public static void main(String[] args) {
        fuc22();
        System.out.println("try-catch后语句");
    }

可以看到, 程序已经异常终止了, 没有执行到 System.out.println("after try catch"); 这一行

【异常处理流程总结】

  • 程序先执行 try 中的代码
  • 如果 try 中的代码出现异常, 就会结束 try 中的代码, 看和 catch 中的异常类型是否匹配.
  • 如果找到匹配的异常类型, 就会执行 catch 中的代码
  • 如果没有找到匹配的异常类型, 就会将异常向上传递到上层调用者.
  • 无论是否找到匹配的异常类型, finally 中的代码都会被执行到(在该方法结束之前执行).
  • 如果上层调用者也没有处理的了异常, 就继续向上传递.
  • 一直到 main 方法也没有合适的代码处理异常, 就会交给 JVM 来进行处理, 此时程序就会异常终止.

三、自定义异常类

实现一个用户登陆功能

class Login {
    private String userName = "123";
    private String passWord = "321";

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPassWord() {
        return passWord;
    }

    public void setPassWord(String passWord) {
        this.passWord = passWord;
    }
    public void loginInfo(String userName,String passWord) {
        if(!this.userName.equals(userName)) {
            System.out.println("用户名错误");
            return;
        }
        if(!this.passWord.equals(passWord)) {
            System.out.println("密码错误");
            return;
        }
        System.out.println("登录成功");
    }
}
public class Test {
    public static void main(String[] args) {
        Login login = new Login();
        Scanner scanner = new Scanner(System.in);
       login.loginInfo(scanner.nextLine(),scanner.nextLine());
    }
}

此时我们在处理用户名密码错误的时候可能就需要抛出两种异常. 我们可以基于已有的异常类进行扩展(继承), 创建 和我们业务相关的异常类.

具体方式:

1. 自定义异常类,然后继承自Exception 或者 RunTimeException

2. 实现一个带有String类型参数的构造方法,参数含义:出现异常的原因

public class userNameException extends RuntimeException {
    public userNameException() {
        super();
    }
    public userNameException(String s) {
        super(s);
    }
}

public class passWordException extends RuntimeException{
    public passWordException(){
        super();
    }
    public passWordException(String s) {
        super(s);
    }
}

login代码更改为

class Login {
    private String userName;
    private String passWord;

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPassWord() {
        return passWord;
    }

    public void setPassWord(String passWord) {
        this.passWord = passWord;
    }
    public void loginInfo(String userName,String passWord) {
        if(!this.userName.equals(userName)) {
            throw new userNameException("用户名错误");
        }
        if(!this.passWord.equals(passWord)) {
           throw new passWordException("密码错误");
        }
        System.out.println("登录成功");
    }
}

测试一下

public class Test {
    public static void main(String[] args) {
        Login login = new Login();
        login.setUserName("123");
        login.setPassWord("123");
        try {
            login.loginInfo("321","123");
        }catch (userNameException e) {
            e.printStackTrace();
        }catch (passWordException e) {
            e.printStackTrace();
        }
    }
}

注意事项

自定义异常通常会继承自 Exception 或者 RuntimeException

继承自 Exception 的异常默认是受查异常

继承自 RuntimeException 的异常默认是非受查异常

  • 14
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值