2012-09-13 53 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;会有同样的效果,你想达到什么。