1. 程式人生 > >try-finally塊

try-finally塊

本文講述的是Java中try finally程式碼塊執行順序,和當其存在於迴圈中的時候的跳出和執行問題。白話,也要簡化,一段程式碼,來說明問題

  /**
	 * @author lihzh
	 * @date 2012-6-8 下午9:21:22
	 * @blog http://www.coderli.com
	 */
	public static void main(String[] args) {
		for (int i = 0; i < 10; i++) {
			System.out.println("Begin loop: " + i);
			if (i == 2) {
				System
.out.println("Continue: " + i); continue; } try { System.out.println("i = " + i); if (i == 4) { System.out.println("In try continue: " + i); continue; } if (i == 5) { return; } } finally { System.out.println("This is finally. " + i); } } }

執行結果:

Begin loop: 0
i = 0
This is finally. 0
Begin loop: 1
i = 1
This is finally. 1
Begin loop: 2
Continue: 2
Begin loop: 3
i = 3
This is finally. 3
Begin loop: 4
i = 4
In try continue: 4
This is finally. 4
Begin loop: 5
i = 5
This is finally. 5

如果還沒看明白,那我再囉嗦兩句:finally就是最後的,跟trycatch是兄弟,就好像正常人走try分支,走著走著你不正常了,就開始走catch

分支,但是不管你正常不正常,最後都要通過最終的檢測,才算完。他們是一個組合。至於外面的for迴圈,就好像你在跑圈,本來每圈你都路過這個關卡(try-finnaly),但是你說,第二圈(i=2)跑一半的時候,突然說,下面我不跑了,我要開始跑第三圈,那關卡也拿你沒轍。攔不住你。至於跑到第五圈了,你說不行了,我跑不動了,以後都不跑了,那也行你退出了,不過你已經進入關卡了,一樣,唯一的出口就在finally。通過再退出。