1. 程式人生 > >演算法之“try-catch-finally-看程式寫結果”

演算法之“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