算法之“try-catch-finally-看程序写结果”

代码:

public calss Test{
    public static void main(String[] args){
        try{
            test(new int[]{0,1,2,3,4,5,6});
        }catch(Exception e){
           System.out.print("c");
        }
    }

    private static void test(int[] arr){
        for(int i=0;i<arr.length;i++){
            try{
                if(arr[i]%2 == 0){
                    throw new NullPointerException();
                }else{
                    System.out.print(arr[i]);
                }
             }catch(Exception e){
                System.out.print("a");
             } finally{
                System.out.print("b");
             }
        }
    }
}
        

代码运行结果为:

a b1 b a b 3 b a b 5 b a b

如果对程序稍加修改:

如下:

public calss Test{
    public static void main(String[] args){
        try{
            test(new int[]{0,1,2,3,4,5,6});
        }catch(Exception e){
           System.out.print("c");
        }
    }

    private static void test(int[] arr){
        for(int i=0;i<arr.length;i++){
            try{
                if(arr[i]%2 == 0){
                    throw new NullPointerException();
                }else{
                    System.out.print(arr[i]);
                }
             
              } finally{
                System.out.print("b");
             }
        }
    }
}
        

去掉catch代码块之后,当输入arr[0]=0之后,抛出空指针异常,同时执行finally代码块,空指针异常在main函数中得到捕获,所以,输出结果为:b c

 

点赞