Java 异常

130 阅读2分钟

「这是我参与11月更文挑战的第5天,活动详情查看:2021最后一次更文挑战

异常处理:

什么是异常?

1.异常是程序在 编译 或者 执行的过程中 可能出现的问题,注意:语法错误不算在异常体系中。

2.比如:数组索引越界、空指针异常、日期格式化异常,等。。。

为什么要学习异常?

1.异常一旦出现了,如果没有提前处理,程序就会退出JVM虚拟机终止。

2.研究异常并且避免异常,然后提前处理异常,体现的是程序的安全,健壮性。

异常体系:

截屏2021-11-05 下午3.44.26.png

编译时异常和运行时异常 编译时异常就是在编译的时候出现的异常 运行时异常就是在运行时出现的异常。

截屏2021-11-05 下午3.45.34.png

截屏2021-11-05 下午3.47.06.png

运行时异常:

直接继承自RuntimeException或者其子类,编译阶段不会报错,运行时可能出现的错误。

运行时异常示例:

截屏2021-11-05 下午3.50.12.png

运行时异常:一般是程序员业务没有考虑好或者是编程逻辑不严谨引起的程序错误。

public class ExceptionDemo {
    public static void main(String[] args) {
        // 1. 数组索引越界异常:ArrayIndexOutOfBoundsException
        int[] arr = {1,2,3};
        System.out.println(arr[2]);
//        System.out.println(arr[3]);
//        Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds

        // 2. 空指针异常:NullPointerException,直接输出没有问题,但是
        String name = null;
        System.out.println(name);
//        System.out.println(name.length());
//        Exception in thread "main" java.lang.NullPointerException
        // 调用空指针的变量的功能就会报错
        // 3. 类型转换异常:ClassCastException
        Object o = 23;
//        String a = (String) o;
//        Exception in thread "main" java.lang.ClassCastException: class java.lang.Integer cannot be cast to class java.lang.String

        // 5. 数学操作异常:ArithmeticException
//        int c = 10/0;
//        Exception in thread "main" java.lang.ArithmeticException: / by zero
        // 6. 数字转换异常:NumberFormatException
        String number = "23ddd";
//        Integer it = Integer.valueOf(number);
//        Exception in thread "main" java.lang.NumberFormatException: For input string: "23ddd"
//        System.out.println(it + 1);
        System.out.println("程序结束。。。。。。");
    }
}

编译时异常

public class ExceptionDemo {
    public static void main(String[] args) throws ParseException {
        String date = "2015-01-12 10:23:21";
        // 创建一个简单日期格式化类,解析字符串时间成为日期对象。
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date d = sdf.parse(date);
        System.out.println(d);
    }
}

截屏2021-11-05 下午4.19.28.png

截屏2021-11-05 下午4.20.00.png

异常的默认异常处理机制:

截屏2021-11-05 下午4.21.46.png

public class ExceptionDemo {
    public static void main(String[] args) {
        System.out.println("程序开始。。。。。。");
        chu(10,0);
        System.out.println("程序结束。。。。。。");
    }

    public static void chu(int a, int b){
        System.out.println(a);
        System.out.println(b);
        int c = a/b;
        System.out.println(c);
    }
}

截屏2021-11-05 下午4.27.19.png

截屏2021-11-05 下午4.28.53.png