异常处理

Lambda表达式是Java 8新引入的一种语法,是一种紧凑的传递代码的方式。

理解Lambda表达式,我们先回顾一下接口、匿名内部类和代码传递。

try-catch-finally

    public static void main(String[] args) {
        System.out.println(" =========== 除法计算开始 ===========");
        try {
            int x = 1;
            int y = 0;
            System.out.println("除法计算:" + (x / y));
        // 只有一个catch,只能处理一个异常, 如果存在其他没有处理的异常, 依次会导致程序中断执行
        } catch (ArithmeticException ex) { // class ArithmeticException extends RuntimeException 运行时异常
            ex.printStackTrace(); // 打印完整的异常信息
            System.out.println("-------- 在finally块之前执行!!! --------");
        } finally {
            //不管异常是否catch处理完,都执行finally(除了一种情况,存在System.exits())
            System.out.println("-------- 不管是否出现异常都执行!-------- ");
        }

//      如果异常没有全部catch,那么这里就不会执行finally后面的代码!!!
        System.out.println("=========== 除法结束 ===========");
    }

结果:

 =========== 除法计算开始 ===========
java.lang.ArithmeticException: / by zero at com.study.ExceptionDemo.main(ExceptionDemo.java:12)
-------- 在finally块之前执行!!! --------
-------- 不管是否出现异常都执行!-------- 
=========== 除法结束 ===========
    public static void main(String[] args) {
        System.out.println(" =========== 除法计算开始 ===========");
        try {
            int x = Integer.parseInt(args[0]);
            int y = Integer.parseInt(args[1]);
            System.out.println("除法计算:" + (x / y));
        // 只有一个catch,只能处理一个异常, 如果存在其他没有处理的异常, 依次会导致程序中断执行
        } catch (ArithmeticException ex) { // class ArithmeticException extends RuntimeException 运行时异常
            ex.printStackTrace(); // 打印完整的异常信息
            System.out.println("-------- 在finally块之前执行!!! --------");
        } finally {
            //不管异常是否catch处理完,都执行finally(除了一种情况,存在System.exits())
            System.out.println("-------- 不管是否出现异常都执行!-------- ");
        }

//      如果异常没有全部catch,那么这里就不会执行finally后面的代码!!!
        System.out.println("=========== 除法结束 ===========");
    }
  • catch捕获的异常没有成功,所以直接中断了程序

执行结果:

 =========== 除法计算开始 ===========
-------- 不管是否出现异常都执行!-------- 
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
	at com.study.ExceptionDemo.main(ExceptionDemo.java:8)

throws

异常的父子关系:
Throwable
    Error;Exception
        RuntimeException;CheckedException
            ArithmeticException,NullPointerException,
            NumberFormatException,ArrayIndexOutOfBoundsException;ClassCastException 

Error: 此时的程序没执行,无论用户怎样处理,都处理不了 
Exception: 程序运行时产生的异常,用户可以处理(后异常处理)
RuntimeException与CheckedException区别 
CheckedException定义的异常◆必须◆被处理,而RuntimeException的异常可以★选择性处理★
posted @ 2023-06-01 14:14  allenwork  阅读(53)  评论(0)    收藏  举报