Using 'continue with label' to reach an inner for loop [closed]

与世无争的帅哥 提交于 2019-12-14 03:34:13

问题


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;
    }
}

I would like to continue at a loop that is inside the try catch block. Is this possible?

EDIT: Sorry, I was not clear on why I couldn't move the try catch to inside the for loop. (edited snippet) If I put the try-catch inside the for loop, the calls inside won't be able to access the ImportantObject.. This is where I was stuck.

EDIT2: Okay, I resolved my problem, albeit without continue with label! I guess the answer to my question is a simple 'no'. Bad habits might be all over the place, but my assignments due in two hours. what can i say :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:


No, it is not possible, since you are already outside of the scope of the try block.

Why not just move the try catch inside the for loop?

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



回答2:


Do you mean you want to do this?

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



回答3:


I think a simple continue; will have same effect, what you want to achieve.



来源:https://stackoverflow.com/questions/12414378/using-continue-with-label-to-reach-an-inner-for-loop

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!