In this code sample, is there any way to continue on the outer loop from the catch block?
while
{
// outer loop
while
{
// inner loop
try
{
throw;
}
catch
{
// how do I continue on the outer loop from here?
continue;
}
}
}
Use an own exception type, e.g., MyException. Then:
This will work for continuing and breaking out of several levels of nested while statements. Sorry for bad formatting ;)
Use
break
in the inner loop.I think the best way to accomplish this would be to use the break statement. Break ends the current loop and continues execution from where it ends. In this case, it would end the inner loop and jump back into the outer while loop. This is what your code would look like:
I believe that is what you were looking to be accomplished, correct? Thanks!
UPDATE: This question was inspiration for my article on this subject. Thanks for the great question!
"continue" and "break" are nothing more than a pleasant syntax for a "goto". Apparently by giving them cute names and restricting their usages to particular control structures, they no longer draw the ire of the "all gotos are all bad all the time" crowd.
If what you want to do is a continue-to-outer, you could simply define a label at the top of the outer loop and then "goto" that label. If you felt that doing so did not impede the comprehensibility of the code, then that might be the most expedient solution.
However, I would take this as an opportunity to consider whether your control flow would benefit from some refactoring. Whenever I have conditional "break" and "continue" in nested loops, I consider refactoring.
Consider:
Two refactoring techniques:
First, extract the inner loop to a method:
Second, can all the loops be eliminated? If you are looping because you are trying to search for something, then refactor it into a query.
If there are no loops then there is no need to break or continue!
Problem solved. (what?? Why are you all giving me that dirty look?)
Swap the try/catch structure with the inner while loop: