作者forris (喬巴)
看板java
標題[問題] try-catch-finally 敘述
時間Tue Apr 8 01:15:51 2008
有一個程式是這樣的:
public class test{
public static void main(String[] args){
int x = 0;
while (x<10){
try{
if (x==3) continue;
if (x==4) break;
}
finally{
System.out.println("x="+x);
if (x==4) continue;
x = x + 1;
}
}
System.out.println("final x="+x);
}
}
執行結果會是:
x=0
x=1
x=2
x=3
x=4
x=4
x=4
......
這是一個無窮迴圈
問為什麼 x=3 and x=4 竟會執行?且 x=4 是個無窮迴圈?
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 59.116.193.15
→ forris:continue and break 沒有發生作用? 04/08 01:16
推 slalala:FINALLY一定會執行 無論有無break 04/08 02:31
推 AI3767:這很明顯啊@@ 仔細看看當x為4時, 每行是怎麼執行的... 04/08 10:28
推 heal92013:在下試了一下,如果把final中的if那一行//後就有答案了 04/08 10:59
推 fuu0115:break-> if (x==4) cont';->x還是4 就變無窮迴圈了 04/08 16:27
推 Lecwar:x=4的時候在finally裡就不會再增加..當然就無窮loop囉 04/09 16:14