• Java学习苦旅(十五)——异常


    本篇博客将讲解Java中的异常。

    异常简介

    什么是异常

    所谓异常指的就是程序在 运行时 出现错误时通知调用者的一种机制。

    关键字运行时有些错误是这样的,比如将 System.out.println 拼写错了, 写成了 system.out.println. 此时编译过程中就会出错, 这是编译期出错。而运行时指的是程序已经编译通过得到了class文件了,再由JVM执行过程中出现的错误。

    异常的种类有很多,不同种类的异常具有不同的含义,也有不同的处理方式。

    常见的异常

    除以0

    System.out.println(10/0);
    
    • 1

    结果为:

    image-20220704172119150

    数组下标越界

    int[] array = {1,2,3};
    System.out.println(array[10]);
    
    • 1
    • 2

    结果为:

    image-20220704172231216

    访问null对象

    public class TestDemo {
        public int a = 10;
        public static void main(String[] args) {
            TestDemo m = null;
            System.out.println(m.a);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    结果为:

    image-20220704172335211

    防御式编程

    错误在代码中是客观存在的,因此我们要让程序出现问题的时候及时通知程序员,我们有两种主要的方式:

    LBYL:Look Before You Leap。在操作之前就做充分的检查。

    EAFP:It’s Easier to Ask Forgiveness than Permission。“事后获取原谅比事前获取许可更容易”。也就是先操作,遇到问题再处理。

    异常的核心思想就是 EAFP。

    异常的好处

    例如写这样一段代码:

    LBYL风格的代码(不使用异常)

    boolean ret = false;
    ret = 登陆游戏();
    if (!ret) {
     处理登陆游戏错误;
        return; 
    }
    ret = 开始匹配();
    if (!ret) {
     处理匹配错误;
        return; 
    }
    ret = 游戏确认();
    if (!ret) {
     处理游戏确认错误;
        return; 
    }
    ret = 选择英雄();
    if (!ret) {
        处理选择英雄错误;
        return; 
    }
    ret = 载入游戏画面();
    if (!ret) {
     处理载入游戏错误;
        return; 
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26

    EAFP风格的代码(使用异常)

    try {
        登陆游戏();
        开始匹配();
        游戏确认();
        选择英雄();
        载入游戏画面();
       ...
    } catch (登陆游戏异常) {
        处理登陆游戏异常;
    } catch (开始匹配异常) {
     处理开始匹配异常;
    } catch (游戏确认异常) {
     处理游戏确认异常;
    } catch (选择英雄异常) {
     处理选择英雄异常;
    } catch (载入游戏画面异常) {
     处理载入游戏画面异常; 
    }
    ...
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    对比两种不同风格的代码,我们可以发现,使用第一种方式,正常流程和错误处理流程代码混在一起,代码整体显的比较混乱。而第二种方式正常流程和错误流程是分离开的,更容易理解代码。

    异常的基本用法

    捕获异常

    基本语法

    try{ 
    	有可能出现异常的语句 ; 
    } catch (异常类型 异常对象) {
    } 
    ... 
    finally {
    	异常的出口
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • try代码块中放的是可能出现异常的代码。
    • catch代码块中放的是出现异常后的处理行为。
    • finally代码块的代码用于处理善后工作,会在最后执行。
    • 其中catch和finally都可以根据情况选择加或者不加。

    代码示例1

    int[] array = {1,2,3};
    System.out.println("before");
    System.out.println(array[100]);
    System.out.println("after");
    
    • 1
    • 2
    • 3
    • 4

    执行结果为:

    image-20220704172432630

    因此,一旦出现异常,程序就终止了。after没有正确输出。

    代码示例2

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

    int[] array = {1,2,3};
    try {
        System.out.println("before");
        System.out.println(array[100]);
        System.out.println("after");
    } catch (ArrayIndexOutOfBoundsException e) {
        e.printStackTrace();
    }
    System.out.println("======================");
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    执行结果为:

    image-20220704172527317

    我们发现,一旦 try 中出现异常,那么 try 代码块中的程序就不会继续执行,而是交给 catch 中的代码来执行,catch 执行完毕会继续往下执行。

    关于异常的处理方式

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

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

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

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

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

    关于调用栈

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

    代码示例3

    catch 只能处理对应种类的异常,例如:

    int[] array = {1,2,3};                       
    try {                                        
        System.out.println("before");            
        array = null;                            
        System.out.println(array[100]);          
        System.out.println("after");             
    } catch (ArrayIndexOutOfBoundsException e) { 
        e.printStackTrace();                     
    }                                            
    System.out.println("======================");
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    运行结果为:

    image-20220704172633590

    此时,catch 语句不能捕获到刚才的空指针异常,因为异常类型不匹配。

    代码示例4

    int[] array = {1,2,3};
    try {
        System.out.println("before");
        array = null;
        System.out.println(array[100]);
        System.out.println("after");
    } catch (ArrayIndexOutOfBoundsException e) {
        e.printStackTrace();
    } catch (NullPointerException e) {
        e.printStackTrace();
    }
    System.out.println("======================");
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    执行结果为:

    image-20220704172740764

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

    catch (ArrayIndexOutOfBoundsException | NullPointerException e) {
        ...
    }
    
    • 1
    • 2
    • 3

    代码示例5

    一个catch可以捕获所有异常,但不推荐,例如:

    int[] array = {1,2,3};
    try {
        System.out.println("before");
        array = null;
        System.out.println(array[100]);
        System.out.println("after");
    } catch (Exception e) {
        e.printStackTrace();
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    执行结果为:

    image-20220704172822025

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

    catch捕获异常的时候,从上到下,最好是子类到父类。

    代码示例6

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

    int[] array = {1,2,3};
    try {
        System.out.println("before");
        array = null;
        System.out.println(array[100]);
        System.out.println("after");
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        System.out.println("finally code");
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    执行结果为:

    image-20220704173054110

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

    代码示例7

    将 Scanner 对象在 try 的 ( ) 中创建,就能保证在 try 执行完毕后自动调用 Scanner的 close 方法,例如:

    try (Scanner sc = new Scanner(System.in)) {
        int num = sc.nextInt();
        System.out.println("num = " + num);
    } catch (Exception e) {
        e.printStackTrace();
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    代码示例8

    finally当中尽量避免出现return,例如:

    public static int fun(int n) {
        try {
            return n;
        } catch (NullPointerException e) {
            e.printStackTrace();
        } finally {
            return 100;
        }
    }
    public static void main(String[] args) {
        System.out.println(fun(10));
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    执行结果为:

    image-20220704173121172

    异常处理流程

    • 程序先执行 try 中的代码。

    • 如果 try 中的代码出现异常,就会结束 try 中的代码,观察和 catch 中的异常类型是否匹配。

    • 如果找到匹配的异常类型,就会执行 catch 中的代码。

    • 如果没有找到匹配的异常类型,就会将异常向上传递到上层调用者。

    • 无论是否找到匹配的异常类型,finally 中的代码都会被执行到(在该方法结束之前执行)。

    • 如果上层调用者也没有处理的了异常,就继续向上传递。

    • 一直到 main 方法也没有合适的代码处理异常,就会交给 JVM 来进行处理,此时程序就会异常终止。

    抛出异常

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

    public static int divide(int x, int y) {
        if (y == 0) {
            throw new ArithmeticException("抛出除 0 异常");
        }
        return x / y;
    }
    public static void main(String[] args) {
        System.out.println(divide(10, 0));
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    执行结果为:

    image-20220704173210153

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

    Java异常体系

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

    image-20220704173239025

    • 顶层类Throwable派生出两个重要的子类:ErrorException

    • 其中Error指的是 Java 运行时内部错误和资源耗尽错误,应用程序不抛出此类异常。这种内部错误一旦出现,除了告知用户并使程序终止之外,再无能无力。这种情况很少出现。

    • Exception是我们程序猿所使用的异常类的父类。

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

    Java语言规范将派生于Error类或RuntimeException类的所有异常称为 非受查异常,所有的其他异常称为 受查异常

    如果一段代码可能抛出 受查异常,那么必须显式进行处理,例如:

    public static String readFile() {
        File file = new File("d:/test.txt");
        Scanner sc = new Scanner(file);
        return sc.nextLine();
    }
    
    public static void main(String[] args) {
        System.out.println(readFile());
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    执行结果为:

    image-20220704173521379

    因此需要进行显示处理,显示处理的方法有两种:

    • 使用try catch包裹起来
    public static String readFile() {
        File file = new File("d:/test.txt");
        Scanner sc = null;
        try {
            sc = new Scanner(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return sc.nextLine();
    }
    
    public static void main(String[] args) {
        System.out.println(readFile());
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    执行结果为:

    image-20220704173609699

    • 在方法上加上异常说明,相当于将处理动作交给上级调用者
    public static String readFile() throws FileNotFoundException {
        File file = new File("d:/test.txt");
        Scanner sc = new Scanner(file);
        return sc.nextLine();
    }
    
    public static void main(String[] args) {
        try {
            System.out.println(readFile());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    执行结果为:

    image-20220226210950644

    自定义异常类

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

    class NameException extends RuntimeException {
        public NameException(String message) {
            super(message);
        }
    }
    
    class PasswordException extends RuntimeException {
        public PasswordException(String message) {
            super(message);
        }
    }
    
    public class TestDemo2 {
        private static final String name = "abc";
        private static final String password = "123456";
    
        public static void login(String name, String password) throws NameException,PasswordException {
            if (!TestDemo2.name.equals(name)) {
                throw new NameException("用户名错误");
            }
            if (!TestDemo2.password.equals(password)) {
                throw new PasswordException("密码错误");
            }
        }
    
        public static void main(String[] args) {
            try {
                login("abc","12345");
            } catch (NameException e){
                System.out.println("用户名错误!");
            } catch (PasswordException e) {
                System.out.println("密码错误!");
            } finally {
                System.out.println("finally执行了!");
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37

    执行结果为:

    image-20220226225711288

    注意事项

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

    结尾

    本篇博客到此结束。
    上一篇博客:Java学习苦旅(十四)——String
    下一篇博客预告:Java学习苦旅(十六)——List

  • 相关阅读:
    STC15单片机-无线通讯(WIFI模块)
    Spring面试题16:Spring框架中的单例bean是线程安全的吗?Spring框架中bean的生命周期?哪些是重要的bean生命周期方法?
    【In-Context Learning】Meta-learning via Language Model In-context Tuning
    利用手机摄像头采集图片运行ORB-SLAM2
    模拟相机拍照——对文档进行数据增强
    Linux驱动开发 问题随笔
    【Hack The Box】Linux练习-- Frolic
    Mybatis——动态sql和分页
    什么是HTTP头部(HTTP headers)?
    2023江苏师范大学计算机考研信息汇总
  • 原文地址:https://blog.csdn.net/m0_53408775/article/details/125605312