謹慎 try-finally

imk_發表於2020-10-22

例 1:不使用 try-finally 包裹 continue

public class Test {

    public static void main(String[] args) {
        int counter = 10;
        
        while (counter > 0) {
            counter--;

            if (counter % 2 == 0) {
                System.out.println("continue");
                continue;
            }

            System.out.println(counter);
        }
    }
}

控制檯輸出:

9
continue
7
continue
5
continue
3
continue
1
continue

例 2:使用 try-finally 包裹 continue

public class Test {

    public static void main(String[] args) {
        int counter = 10;
        while (counter > 0) {
            counter--;
            try {
                if (counter % 2 == 0) {
                    continue;
                }
            } finally {
                System.out.println(counter);
            }
        }
     }
}

控制檯輸出:

9
continue
8
7
continue
6
5
continue
4
3
continue
2
1
continue
0

相關文章