使用'continue with label'来达到内部for循环

时间:2012-09-13 20:35:02

标签: java continue

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块内部的循环中。这可能吗?

编辑:对不起,我不清楚为什么我无法将try catch移到for循环中。 (编辑片段)如果我把try-catch放在for循环中,里面的调用将无法访问ImportantObject。这就是我被卡住的地方。

EDIT2:好的,我解决了我的问题,虽然没有继续标签!我想我的问题的答案是一个简单的'不'。坏习惯可能到处都是,但我的作业需要两个小时。我能说什么: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;
    }
}

3 个答案:

答案 0 :(得分:2)

不,这是不可能的,因为你已经超出了try块的范围。

为什么不在for循环中移动try catch?

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

答案 1 :(得分:1)

你的意思是你想要这样做吗?

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

答案 2 :(得分:0)

我认为一个简单的continue;会产生同样的效果,你想要实现的目标。