Java基础_异常

异常体系介绍

在这里插入图片描述

  • 异常是什么?
    • 程序中可能出现的问题
  • 异常体系的最上层父类?异常分为几类
    • 父类:Exception
    • 异常分为两类:编译时异常、运行时异常
  • 编译时异常和运行时异常的区别
    • 编译时异常:没有继承RuntimeException的异常,直接继承于Exception。编译阶段就会错误提示。
    • 运行时异常:RuntimeException本身和子类。编译阶段没有错误提示,运行时出现的。

编译时异常和运行时异常

  • 两者的区别
    • 编译时异常:除了RuntimeException和他的子类,其他都是编译时异常。编译阶段需要进行处理,作用在于提醒程序员。
    • 运行时异常:RuntimeException本身和所有子类,都是运行时异常。编译阶段不报错,是程序运行时出现的。一般是由于参数传递错误带来的问题。

异常的作用

  • 用来查询bug的关键参考信息
  • 作为方法内部的一种特殊返回值,以便通知调用者底层的执行情况

异常的处理方式

JVM默认的处理方式

  • JVM默认的处理方式
    • 把异常的名称,异常原因及异常出现的位置等信息输出在了控制台
    • 程序停止执行,下面的代码不会再执行了

自己处理(捕获异常)

try…catch

public class ExceptionDemo6 {
    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4, 5};

        try{
            System.out.println(arr[10]); // 此处出现了异常,程序会在这里创建一个 ArrayIndexOutOfBoundsException 对象
                                        // new ArrayIndexOutOfBoundsException();
                                        // 拿着这个对象到catch的小括号中对比,看括号中的遍历是否可以接收这个对象
                                        // 如果能接收,表视该异常被捕获,执行catch中的代码
                                        // 当catch里面的所有代码执行完毕,继续执行try...catch体系下面的其他代码
        }catch (ArrayIndexOutOfBoundsException e){
            System.out.println("索引越界了");
        }

        System.out.println("看看我执行了吗");
    }
}

灵魂四问

  • 如果try中没有遇到问题,怎么执行
    • 会把try里面所有的代码全部执行完毕,不会执行catch里面的代码
  • 如果try中可能会遇到多个问题,怎么执行
    • 会写多个catch与之对应,父类异常需要写在下面
  • 如果try中遇到的问题没有被捕获,怎么执行
    • 相当于try…catch白写了,当前异常会交给虚拟机处理
  • 如果try中遇到问题,那么try下面的其他代码还会执行吗
    • 不会执行了。try中遇到问题,直接跳转到对应的catch,如果没有对应的catch与之匹配,则交给虚拟机处理

Throwable的成员方法

public class ExceptionDemo11 {
    public static void main(String[] args) {
        /**
         * public String getMessage()       返回此可抛出的建端描述
         * public String toString()         返回此throwable的详细消息字符串
         * public void printStackTrace()    在底层是利用System.err.println进行输出
         *                                  把异常的错误信息以红色字体输出在控制台,不会中断程序运行
         */

        int[] arr = {1,2,3,4};
        try{
            System.out.println(arr[10]);
        }catch (ArrayIndexOutOfBoundsException e){
            System.out.println(e.getMessage()); // Index 10 out of bounds for length 4
            System.out.println(e.toString()); // java.lang.ArrayIndexOutOfBoundsException: Index 10 out of bounds for length 4
            e.printStackTrace();
        }
        System.out.println("看看我执行了吗");
    }
}

抛出处理

public class ExceptionDemo12 {
    public static void main(String[] args) {


        int[] arr = null;
        int num = 0;
        try {
            num = getMax(arr);
        } catch (NullPointerException e) {
            System.out.println("空指针异常");
        } catch (ArrayIndexOutOfBoundsException e){
            System.out.println("索引越界异常");
        }
        System.out.println(num);
    }

    private static int getMax(int[] arr) /*throws NullPointerException,ArrayIndexOutOfBoundsException*/ {
        if(arr == null){
            throw new NullPointerException();
        }
        if(arr.length == 0){
            throw new ArrayIndexOutOfBoundsException();
        }
        int ret = arr[0];
        for(int i=1;i<arr.length;i++){
            if(arr[i] > ret){
                ret = arr[i];
            }
        }
        return ret;
    }
}

综合练习

public class ExceptionDemo13 {
    public static void main(String[] args) {
        /**
         * 学生的名字长度为[3, 10]
         * 学生的年龄大小为[18, 40];
         */
        Scanner sc = new Scanner(System.in);

        Student stu = new Student();

        while (true) {
            try {
                System.out.println("请输入学生的名字");
                String name = sc.nextLine();
                stu.setName(name);
                System.out.println("请输入学生的年龄");
                String ageStr = sc.nextLine();
                int age = Integer.parseInt(ageStr);
                stu.setAge(age);
                break;
            } catch (NumberFormatException e) {
                System.out.println("年龄的格式有异常");
            } catch (RuntimeException e) {
                System.out.println("名字的长度或者年龄的大小有异常");
            }
        }

        System.out.println(stu.toString());

    }
}

public class Student {
    private String name;
    private int age;

    ...

    public void setName(String name) {
        if(name.length() < 3 || name.length() > 10){
            throw new RuntimeException();
        }
        this.name = name;
    }

    public void setAge(int age) {
        if(age < 18 || age > 40){
            throw new RuntimeException();
        }
        this.age = age;
    }

    @Override
    public String toString() {
        return "Student{" + "name='" + name + '\'' + ", age=" + age + '}';
    }
}

自定义异常

  1. 定义异常类
  2. 写继承关系
  3. 空参构造
  4. 带参构造
public void setAge(int age) {
    if(age < 18 || age > 40){
        throw new AgeOutOfBoundsException(age+"有误,大小应在[18, 40]");
    }
    this.age = age;
}

public class AgeOutOfBoundsException extends RuntimeException{

    public AgeOutOfBoundsException() {
    }

    public AgeOutOfBoundsException(String message) {
        super(message);
    }
}

来源

黑马程序员. 阿玮Java零基础

Gitee地址

https://gitee.com/yu-ba-ba-ba/awJava

  • 21
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Y_cen

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值