-->

Using 'continue with label' to reach an in

2019-09-20 12:58发布

问题:

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.



标签: java continue