try-finally塊
阿新 • • 發佈:2018-12-23
本文講述的是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就是最後的,跟try和catch是兄弟,就好像正常人走try分支,走著走著你不正常了,就開始走catch