2012-09-13 67 views
-1
while (true) { 
    try { 
     //create ImportantObject 
     LoopToGoTo: 
     for (int i = 0; i < Limit; i++) { 
      //method in here throws the exception 
      //ImportantObject is used in here. 
     } 
    } catch(Exception e) { 
     //report error 
     continue LoopToGoTo; 
    } 
} 

我想繼續在try catch塊內的循環。這可能嗎?使用「繼續使用標籤」達到內部for循環

編輯:對不起,我不清楚爲什麼我不能將try catch移到for循環中。 (編輯過的片段)如果我把try-catch放在for循環中,那裏面的調用將無法訪問ImportantObject ..這就是我被卡住的地方。

編輯2:好的,我解決了我的問題,儘管沒有繼續標籤!我想我的問題的答案是一個簡單的「不」。壞習慣可能遍佈全球,但我的任務在兩個小時內完成。我能說什麼:D

//ImportantClass ImportantObject = null; 
while (!ranOnce) { 
    try { 
     //create ImportantObject 
     ranOnce = true; 
    } catch(Exception e) { 
     //report error 
     continue; 
    } 
} 
for (int i = 0; i < Limit; i++) { 
    try { 
     //method in here throws the exception 
     //ImportantObject is used in here. 
    } catch(Exception e) { 
     //report error 
     continue; 
    } 
} 
+1

你不需要有任何東西,它會繼續for循環。 –

+0

「如果我將try-catch放在for循環中,內部的調用將無法訪問ImportantObject ..這就是我被卡住的地方。」 - 我不明白 - 創建ImportantObject,輸入for循環,然後輸入try循環 - 這不起作用? –

回答

2

不,這是不可能的,因爲你已經超出了try塊的範圍。

爲什麼不直接在for循環中移動try catch?

for (int i = 0; i < Limit; i++) { 
    try { 
     //method in here throws the exception 
    } 
    catch(Exception e) { 
    //report error 
    } 
} 
+0

這基本上是我最終做的。 – James

1

你的意思是你想這麼做嗎?

 for (int i = 0; i < Limit; i++) { 
      try { 
      //method in here throws the exception 
      } catch(Exception e) { 
      //report error 
      } 
     } 
0

我認爲一個簡單的continue;會有同樣的效果,你想達到什麼。