• Java的异常类Exception


    异常是程序中发生的错误事件,它破坏了程序指令的正常流程。

    使用异常

    try{}catch(){}可以捕获代码中的异常,try{}代码块执行过程遇到错误时,就停止继续往下执行,并跳转执行catch(){}
    代码块。不管有没有出现异常最后都会执行finally{}

    try {
        // 代码
    } catch (Exception e) {
        // 处理异常
    } finally {
        // 
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    异常如果没有被捕获,也就是没有被try到,那程序会直接中断停止运行。


    可以有多个catch(){}代码块来识别异常类型,可以根据异常类型判断执行哪个代码块。判断异常类型顺序是从上往下判断的,当遇到属于当前异常的类型就执行当前代码块,执行之后就不会再去往下执行了。相当于if elseif elseif*的关系。

    如下:

    try {
        int i = 10 / 0;
        System.out.println("无法继续执行了");
    } catch (ArithmeticException e) {
        System.out.println("出现表达式异常");
    } catch (Exception e) {
        System.out.println("出现通用异常");
    } finally {
        System.out.println("不管怎样都要执行");
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    手动抛出异常

    可以通过throw手动抛出异常,手动抛出异常在日常开发中经常用到,比如对入参进行判断,如下:对金额大小判断,如果金额小于0,就抛出异常。

    try {
        int money = -1;
        if (money < 0) {
            throw new RuntimeException();
        }
    } catch (RuntimeException e) {
        System.out.println("出现异常啦");
    } finally {
        System.out.println("不管怎样都要执行");
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    异常声明

    Java 鼓励人们把方法可能会抛出的异常告知使用此方法的客户端程序员。这是种优雅的做法,它使得调用者能确切知道写什么样的代码可以捕获所有潜在的异常。

    public class Demo {
        public static void test() throws Exception {
            int i = 10 / 0;
        }
    
        public static void main(String[] args) {
            try {
                test();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    自定义异常

    自定义异常只需要继承一个现有的异常就可以了,如下我们经常用到的业务异常BizException。有错误码和错误信息两个字段。

    public class BizException extends RuntimeException {
        // 错误码
        private Integer code;
    
        // 错误信息
        private String msg;
    
        public BizException(Integer code, String msg) {
            this.code = code;
            this.msg = msg;
        }
    
        // setter getter
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    结语

    关注微信公众号:小虎哥的技术博客,每天一篇文章,让你我都成为更好的自己。

  • 相关阅读:
    AI人工智能(第一天)
    题目78:日志排序
    传统算法与神经网络算法,神经网络算法应用领域
    C语言的传参方式(int x)(int *x)(int &x)
    【快速乘、快速幂】快速乘算法和快速幂算法的思想及其代码实现
    国产化正在成为超融合市场的重要发展方向之一
    浮点数算法:争议和限制
    数据结构初相识
    spark写带sasl认证的kafka
    Django老项目升级到新版本
  • 原文地址:https://blog.csdn.net/qq_28883885/article/details/126158635