Java异常,教课书式知识梳理

hello,家人们!今天的分享是Java异常的知识。

异常的背景

初识异常

我们曾经的代码中已经接触了一些 “异常” 了. 例如:

除以 0:

System.out.println(10 / 0);

在这里插入图片描述

数组下标越界:

public static void main(String[] args) {
        int[] arr = {1, 2, 3};
        System.out.println(arr[100]);
    }

在这里插入图片描述

访问 null 对象:

public class TestDemo4 {

    public int num = 10;
 public static void main(String[] args) {
    TestDemo4 t = null;
    System.out.println(t.num);
    }
  }

在这里插入图片描述

所谓异常指的就是程序在 运行时 出现错误时通知调用者的一种机制…
异常的种类有很多, 不同种类的异常具有不同的含义, 也有不同的处理方式

防御式编程

错误在代码中是客观存在的. 因此我们要让程序出现问题的时候及时通知程序猿. 我们有两种主要的方式:
LBYL: Look Before You Leap. 在操作之前就做充分的检查.
EAFP: It’s Easier to Ask Forgiveness than Permission. “事后获取原谅比事前获取许可更容易”. 也就是先操作, 遇到问题再处理.

这两个概念不要死记硬背!!!
简单理解:

(1)LBYL:过马路,得到同意,你拉起你男(女)朋友的手过去。
(2)EAFP:过马路,没得到同意,你拉起你男(女)朋友的手过去,大不了事后被打一下。
异常的核心思想就是 EAFP

异常的基本用法

捕获异常

基本语法

try{ 
 有可能出现异常的语句 ; 
}[catch (异常类型 异常对象) {
} ... ]
[finally {
 异常的出口
}]

try 代码块中放的是可能出现异常的代码.
catch 代码块中放的是出现异常后的处理行为.
finally 代码块中的代码用于处理善后工作, 会在最后执行.
其中 catch 和 finally 都可以根据情况选择加或者不加

不处理异常

public static void main(String[] args) {
        int[] arr = {1, 2, 3};
        System.out.println("before");
        System.out.println(arr[100]);
        System.out.println("after");
    }

在这里插入图片描述

我们发现一旦出现异常, 程序就终止了. after 没有正确输出

使用 try catch 后的程序执行过程

int[] arr = {1, 2, 3};
try {
    System.out.println("before");
    System.out.println(arr[100]);
    System.out.println("after");
} catch (ArrayIndexOutOfBoundsException e) {
    // 打印出现异常的调用栈
    e.printStackTrace();
}
 System.out.println("after try catch");
    }

在这里插入图片描述

我们发现, 一旦 try 中出现异常, 那么 try 代码块中的程序就不会继续执行, 而是交给 catch 中的代码来执行. catch 执行完毕会继续往下执行.
关于 “调用栈”:

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

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) {
            e.printStackTrace();
        }
        System.out.println("after try catch");
    }

在这里插入图片描述

此时, 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 (ArrayIndexOutOfBoundsException e) {
            System.out.println("这是个数组下标越界异常");
            e.printStackTrace();
        } catch (NullPointerException e) {
            System.out.println("这是个空指针异常");
            e.printStackTrace();
        }
        System.out.println("after try catch");
    }

在这里插入图片描述

一段代码可能会抛出多种不同的异常, 不同的异常有不同的处理方式. 因此可以搭配多个 catch 代码块.
如果多个异常的处理方式是完全相同, 也可以写成这样

catch (ArrayIndexOutOfBoundsException | NullPointerException e) {
 ...
}

也可以用一个 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 进行类型匹配的时候, 不光会匹配相同类型的异常对象, 也会捕捉目标异常类型的子类对象.
如刚才的代码, NullPointerExceptionArrayIndexOutOfBoundsException 都是 Exception 的子类, 因此都能被捕获到.

finally 表示最后的善后工作, 例如释放资源

public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        try {
            int n = scanner.nextInt();
            System.out.println(10/n);
        }catch (InputMismatchException e) {
            e.printStackTrace();
            System.out.println("输入有误!");
        }catch (ArithmeticException e) {
            e.printStackTrace();
            System.out.println("算术异常,可能0作为了除数");
        }finally {
            //一般用作 资源的关闭
            scanner.close();
            System.out.println("finally执行了!");
        }

    }

在这里插入图片描述

无论是否存在异常, finally 中的代码一定都会执行到. 保证最终一定会执行到 Scannerclose方法

使用 try 负责回收资源

刚才的代码可以有一种等价写法, 将 Scanner 对象在 try 的 ( ) 中创建, 就能保证在 try 执行完毕后自动调用 Scanner的 close方法

public static void main(String[] args) {
        try (Scanner scanner = new Scanner(System.in)) {
            int n = scanner.nextInt();
            System.out.println(10 / n);
        } catch (InputMismatchException e) {
            e.printStackTrace();
            System.out.println("输入有误!");
        } catch (ArithmeticException e) {
            e.printStackTrace();
            System.out.println("算术异常,可能0作为了除数");
        } finally {
            //一般用作 资源的关闭
            System.out.println("finally执行了!");
        }

    }

在这里插入图片描述

小技巧
IDEA 能自动检查我们的代码风格, 并给出一些更好的建议.
如我们之前写的代码, 在 try 上有一个 “加深底色” , 这时 IDEA 针对我们的代码提出了一些更好的建议

在这里插入图片描述

此时把光标放在 try 上悬停, 会给出原因. 按下 alt + enter, 会弹出一个改进方案的弹窗. 我们选择其中的
在这里插入图片描述

此时我们的代码就自动被IDEA调整成上面的样式

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

public static void main(String[] args) {
        try {
            func();
        } catch (ArrayIndexOutOfBoundsException e) {
            e.printStackTrace();
        }
        System.out.println("after try catch");
    }
    public static void func() {
        int[] arr = {1, 2, 3};
        System.out.println(arr[100]);
    }

在这里插入图片描述

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

public static void main(String[] args) {
    func1();
      System.out.println("after try catch");
}
public static void func1() {
    int[] arr = {1, 2, 3};
    System.out.println(arr[100]);
}

在这里插入图片描述

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

异常处理流程

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

抛出异常

除了 Java 内置的类会抛出一些异常之外, 程序猿也可以手动抛出某个异常. 使用 throw 关键字完成这个操作

 public static void main(String[] args) {
        System.out.println(divide(10, 0));
    }
    public static int divide(int x, int y) {
        if (y == 0) {
            throw new ArithmeticException("抛出除 0 异常");
        }
        return x / y;
    }

在这里插入图片描述

在这个代码中, 我们可以根据实际情况来抛出需要的异常. 在构造异常对象同时可以指定一些描述性信息

异常说明

我们在处理异常的时候, 通常希望知道这段代码中究竟会出现哪些可能的异常.
我们可以使用 throws 关键字, 把可能抛出的异常显式的标注在方法定义的位置. 从而提醒调用者要注意捕获这些异常

public static void main(String[] args) {
        System.out.println(divide(10, 0));
    }
public static int divide(int x, int y) throws ArithmeticException { 
 if (y == 0) { 
 throw new ArithmeticException("抛出除 0 异常"); 
 } 
 return x / y; 
}

在这里插入图片描述

关于 finally 的注意事项

finally 中的代码保证一定会执行到. 这也会带来一些麻烦

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

在这里插入图片描述

注意:

finally 执行的时机是在方法返回之前(try 或者 catch 中如果有 return 会在这个 return 之前执行 finally). 但是如果finally 中也存在 return 语句, 那么就会执行 finally 中的 return, 从而不会执行到 try 中原有的 return.
一般我们不建议在 finally 中写 return (被编译器当做一个警告)
在这里插入图片描述

Java 异常体系

Java 内置了丰富的异常体系, 用来表示不同情况下的异常.

下图表示 Java 内置的异常类之间的继承关系:

在这里插入图片描述

顶层类 Throwable 派生出两个重要的子类, Error 和 Exception
其中 Error 指的是 Java 运行时内部错误和资源耗尽错误. (应用程序不抛出此类异常).

这种内部错误一旦出现,除了告知用户并使程序终止之外, 再无能无力. 这种情况很少出现.
Exception 是我们程序猿所使用的异常类的父类…

其中 Exception 有一个子类称为 RuntimeException , 这里面又派生出很多我们常见的异常类NullPointerException , IndexOutOfBoundsException 等.

Java语言规范将派生于 Error 类或 RuntimeException 类的所有异常称为 非受查异常, 所有的其他异常称为 受查异常.
如果一段代码可能抛出 受查异常, 那么必须显式进行处理.
在这里插入图片描述在这里插入图片描述

FileNotFoundException 这样的异常就是受查异常. 如果不显式处理, 编译无法通过
显式处理的方式有两种:
a) 使用 try catch 包裹起来

public static void main(String[] args) {
        System.out.println(readFile());
    }
    public static String readFile() {
        File file = new File("D:/text.txt");
        Scanner sc = null;
        try {
            sc = new Scanner(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return sc.nextLine();
    }

在这里插入图片描述

b) 在方法上加上异常说明, 相当于将处理动作交给上级调用者

 public static void main(String[] args) {
        try {
            System.out.println(readFile());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
    public static String readFile() throws FileNotFoundException {
        File file = new File("d:/text.txt");
        Scanner sc = new Scanner(file);
        return sc.nextLine();
    }

在这里插入图片描述

别忘了 IDEA 神奇的 alt + enter, 能够快速修正代码

自定义异常类

Java 中虽然已经内置了丰富的异常类, 但是我们实际场景中可能还有一些情况需要我们对异常类进行扩展, 创建符合我们实际情况的异常…

例如, 我们实现一个用户登陆功能.

public class TestDemo3 { 
 private static String userName = "chen"; 
 private static String password = "123456"; 
 public static void main(String[] args) { 
 login("man", "123456"); 
 } 
 public static void login(String userName, String password) { 
 if (!TestDemo3.userName.equals(userName)) { 
 // TODO 处理用户名错误
 } 
 if (!TestDemo3.password.equals(password)) { 
 // TODO 处理密码错误
 } 
 System.out.println("登陆成功"); 
 } 
}

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

class NameException extends RuntimeException{
    public NameException(String message){
        super(message);
    }
}
class PasswordException extends RuntimeException{
    public PasswordException(String message){
        super(message);
    }
}

public class TestDemo3 {
    private static final String name = "chen";
    private static final String password = "123456";

    public static void login(String name,String password) throws NameException,PasswordException{
        if(!TestDemo3.name.equals(name)){
            //System.out.println("用户名错误!");
            throw new NameException("用户名错误!");
        }
        if(!TestDemo3.password.equals(password)){
            //System.out.println("密码错误!");
            throw new PasswordException("密码错误!");
        }
    }
    public static void main(String[] args) {
try{
    login("chenman","123456");
}catch (NameException e){
    e.printStackTrace();
    System.out.println("用户名错误了!");
}catch (PasswordException e){
    e.printStackTrace();
    System.out.println("密码错误了!");
}finally {
    System.out.println("finally执行了!");
}
        //System.out.println("hello world");
    }
}

在这里插入图片描述注意事项:

自定义异常通常会继承自 Exception 或者 RuntimeException
继承自 Exception 的异常默认是受查异常
继承自 RuntimeException 的异常默认是非受查异常

总结

异常这一块的知识点相对来说是比较简单的,比较容易接受,但是,还是得自己上手才知道。好了,今天的梳理就到这里了,如果对你有帮助,记得给博主点赞哟!加油!让我们一起努力,一起进步!!!

  • 8
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

粉色的志明

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值