异常-多个catch块

来源:互联网 发布:男人穿衣搭配软件 编辑:程序博客网 时间:2024/05/29 11:35

对于有多个catch块时,通常按照“从小到大”的顺序捕获异常,这样才能按照保证逐层捕获,从而避免对父类的大的异常进行了捕获,导致对子类的小的异常无法进行捕获的情况。

    public static void main(String[] args) {        fun2();    }    //捕获异常的顺序不正确时,这样写编译就通不过的    public static void fun1(){        try {            int arr[] = {1,2,6};            System.out.println(arr[3]);        } catch (RuntimeException e) {  //运行时异常            System.out.println("RuntimeException...");        } catch (ArrayIndexOutOfBoundsException e) {  //数组下标访问越界            System.out.println("ArrayIndexOutOfBoundsException...");        } catch (Exception e) {         //异常            System.out.println("Exception...");        }finally{            System.out.println("finally...");        }    }    //按照“从小到大”的原则进行一一捕获    public static void fun2(){        try {            int arr[] = {1,2,6};            System.out.println(arr[3]);        } catch (ArrayIndexOutOfBoundsException e) {  //数组下标访问越界            System.out.println("ArrayIndexOutOfBoundsException...");        } catch (RuntimeException e) {  //运行时异常            System.out.println("RuntimeException...");        } catch (Exception e) {         //异常            System.out.println("Exception...");        }finally{            System.out.println("finally...");        }    }
阅读全文
0 0
原创粉丝点击