JAVA的异常 学习

java 异常

创建场景

int a = 0;
        int b = 0;
        int s = b / a;
        System.out.println(s);

我们的指令 自身不合理,所以java停止执行,后面的语句无法继续执行

异常的继承关系

Exception

  1. ZeroDevisionException

  2. 字典里面没有元素

  3. NullPointer

    各种类型的异常

异常的捕获

对于某些错误,我们不希望程序彻底退出

Scanner sc = new Scanner(System.in);
        System.out.print("Please input 摄氏度:");
        String in = sc.nextLine();
        while (!in.startsWith("q")) {
            int i = 0;
            try {
                i = Integer.parseInt(in);
            }catch (NumberFormatException e) { // 匹配上,说明这种异常我们是有 预案的。。。就没必要结束了
                System.out.println("您的输入不合法,请输入合法的整数");
                System.out.print("Please input 摄氏度:");
                in = sc.nextLine();
                continue;
            }

            double f_ = 9.0 * i / 5.0 +32;
            System.out.println("F is " + f_);


            System.out.println("Please input 摄氏度:");
            in = sc.nextLine();
        }

多种exception的情况

int a = 0;
        int b = 0;
        int s = b / a;
        System.out.println(s);

        Scanner sc = new Scanner(System.in);
        System.out.println("Please input 摄氏度:");
        String in = sc.nextLine();
        while (!in.startsWith("q")) {
            int i = 0;
            try {
                i = Integer.parseInt(in);
            }catch (NumberFormatException  | IndexOutOfBoundsException e) {
                System.out.println("您的输入不合法,请输入合法的整数");
                System.out.println("Please input 摄氏度:");
                in = sc.nextLine();
                continue;
            } catch (Exception e) {

            }

            double f_ = 9.0 * i / 5.0 +32;
            System.out.println("F is " + f_);


            System.out.println("Please input 摄氏度:");
            in = sc.nextLine();
        }

自定义异常

public static void register(String s) throws InvalidPhoneException {

    for (int i = 0; i < s.length(); i ++) {
        char ch = s.charAt(i);
        if (ch < '0' || ch > '9') {
            throw new InvalidPhoneException();
        }
    }

    return ;
}

多级调用的异常

public static void level_1() {
    System.out.println("start 111");
    level_2();
    System.out.println("end 111");
}
public static void level_2() {
    System.out.println("start 222");
    level_3();
    System.out.println("end 222");
}
public static void level_3() {
    System.out.println("start 333");
    int[] arr = new int[2];
    int mynum = 3;
    mynum --;
    for (int i = 0; i <= mynum ; i ++) {
        arr[i] = i;
    }
    System.out.println("end 333");
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值