异常和异常处理的小结

发布于:2022-12-02 ⋅ 阅读:(205) ⋅ 点赞:(0)
public class ExceptionDemo2 {
    public static void main(String[] args) {
        System.out.println("开始");
        method();
        System.out.println("结束");
    }
    public  static void method(){
        try {
            int arr[] ={1,2,3,4,5};
            System.out.println(arr[6]);//new ArrayIndexOutOfBoundsException();
        }catch(ArrayIndexOutOfBoundsException e){
//            System.out.println("您访问数组的索引不存在");
            e.printStackTrace();

        }



    }
}

异常  Exception 1.error  2.Throwable

2.1 RuntimeException (运行时异常)2.2 受检异常 除了运行时异常都是编译时异常

public class ExceptionDemo3 {
    public static void main(String[] args) {
        method1();
        method2();


    }

    //编译时异常
    public static void method1() {
        try {
            String s = "2022-10-03";
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-DD");
            Date d = sdf.parse(s);
            System.out.println(d);
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
//运行时异常
    public static void method2() {
        try {
            int arr[] = {1, 2, 3, 4, 5};
            System.out.println(5);
        }catch (ArrayIndexOutOfBoundsException e){
            e.printStackTrace();
        }
    }
}

throws异常

* 编译时异常必须进行处理 两种方案:try   catch... 或者throws处理  采用throws处理,将来谁调用谁处理

*运行时异常可以不处理,出现问题后 需要回来修改代码

自定义异常

1.就是定义一个异常继承Exception  写这个 类的无参构造和有参构造message以便于可以打印出异常信息

2.写一个类 一个方法检查这个异常是否能正常运行 这个方法有个参数写逻辑运行  运行这个自定义异常throw now xxxException("写这个异常的信息")  同时在方法上抛出自定义异常

3.写一个测试类测试该方法 可以写一个键盘输入来测试 创建对象 调用方法 传参测试

可以直接抛出异常

 也可以catch住

本文含有隐藏内容,请 开通VIP 后查看

网站公告

今日签到

点亮在社区的每一天
去签到