韩顺平Java23——异常

异常(Exception)

  • 基本概念

快捷键:ctrl+alt+t

 

  • 异常体系图(重点!!!)

 ps:这里只写了五个基本的运行异常,想自己看的可以在idea里通过追throwable类来查看

常见运行时异常

 常见编译异常

异常处理的两种方式

  • try-catch-finally

 当程序捕获到异常的时候立即停止继续执行,转而跳到catch语句

细节:

 

小结:

  • throws

 throws抛出异常是由(函数等的)调用者来处理的

这里是编译异常必须处理,不处理则报错

这里则是运行时异常不处理也不会报错,因为有默认处理机制

  如果异常一直没有被处理,则转交给JVM处理,jvm处理的方式是立即停止程序并打印异常(相当于默认处理,所以类默认带有一个throws),在同一个类中throws和try-catch语句二选一即可,如果程序员没有显式地处理异常则默认采用throws方法抛出异常

使用细节:

 自定义异常

 

  •  入门案例:
/**
 * @author 紫英
 * @version 1.0
 * @discription 自定义异常
 */
public class Exception03 {
    public static void main(String[] args) {
        int age = 198;
        if (!(age>18 && age <120)){
            throw new AgeException("年龄需要在18-120之间!");
        }
        System.out.println("age="+age);

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

 这里输出了自定义异常信息

  • throw和throws的区别

 刚才在方法内抛出自定义异常用的就是throw关键字,而throws是用在方法声明的地方

public  void f1() throws ArithmeticException{
        int num = 4;
        int a=num/0;
    }
  • 练习:

1.

 因为一个函数只能存在一个return,而finally必须执行所以返回值为finally的4

2.注意

 道理同上,走到catch语句的时候准备return但是还没有走finally,所以先将返回值的3存在一个temp变量中(系统干的),然后程序继续执行finally的代码块,执行完毕后再return刚才的3

所以结果为:

 3.

/**
 * @author 紫英
 * @version 1.0
 * @discription 异常练习
 */
public class Exception02 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int num = 0;
        while (true){

            System.out.println("请输入一个整数:");
            try {
                num=Integer.parseInt(scanner.next());
                break;
            } catch (NumberFormatException e) {
                System.out.println("输入的不是整数!");
            }

        }
        System.out.println("num="+num);
    }
}

4.

/**
 * @author 紫英
 * @version 1.0
 * @discription 异常练习——两数相除,对数据格式不正确、缺少参数、除0进行异常处理
 */
public class ExceptionHomework01 {
    public static void main(String[] args) {

        try {
            if (args.length != 2) {
                throw new ArrayIndexOutOfBoundsException("参数个数不对");
            }
           int n1= Integer.parseInt(args[0]);
           int n2= Integer.parseInt(args[1]);
           double res = cal(n1,n2);
            System.out.println("res="+res);

        } catch (ArrayIndexOutOfBoundsException e) {
           e.printStackTrace();
        }catch (NumberFormatException e){
            System.out.println("参数格式不正确!");
        }catch (ArithmeticException e){
            System.out.println("除0异常");
        }

    }

    public static int cal(int n1, int n2) {
        return n1 / n2;
    }
}

命令行传参数:

 

posted @ 2021-12-25 16:09  紫英626  阅读(71)  评论(0编辑  收藏  举报

紫英