Continue in nested while loops

C#LoopsWhile LoopContinue

C# Problem Overview


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

C# Solutions


Solution 1 - C#

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:

successfulCandidate = null;
foreach(var candidate in candidates)
{
  foreach(var criterion in criteria)
  {
    if (!candidate.Meets(criterion))
    {  // TODO: no point in continuing checking criteria.
       // TODO: Somehow "continue" outer loop to check next candidate
    }
  }
  successfulCandidate = candidate;
  break;
}
if (successfulCandidate != null) // do something

Two refactoring techniques:

First, extract the inner loop to a method:

foreach(var candidate in candidates)
{
  if (MeetsCriteria(candidate, criteria))
  { 
      successfulCandidate = candidate;
      break;
  }
}

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.

var results = from candidate in candidates 
              where criteria.All(criterion=>candidate.Meets(criterion))
              select candidate;
var successfulCandidate = results.FirstOrDefault();
if (successfulCandidate != null)
{
  do something with the candidate
}

If there are no loops then there is no need to break or continue!

Solution 2 - C#

    while
    {
       // outer loop
    
       while
       {
           // inner loop
           try
           {
               throw;
           }
           catch 
           {
               // how do I continue on the outer loop from here?
               goto REPEAT;
           }
       }
       // end of outer loop
REPEAT: 
       // some statement or ; 
    }

Problem solved. (what?? Why are you all giving me that dirty look?)

Solution 3 - C#

You can use a break; statement.

while
{
   while
   {
       try
       {
           throw;
       }
       catch 
       {
           break;
       }
   }
}

Continue is used to jump back to the top of the current loop.

If you need to break out more levels than that you will either have to add some kind of 'if' or use the dreaded/not recommended 'goto'.

Solution 4 - C#

Swap the try/catch structure with the inner while loop:

while {
  try {
    while {
      throw;
    }
  }
  catch {
    continue;
  }
}

Solution 5 - C#

No.
I suggest, extracting the inner loop into a separate method.

while
{
   // outer loop
       try
       {
           myMethodWithWhileLoopThatThrowsException()
       }
       catch 
       {
           // how do I continue on the outer loop from here?
           continue;
       }
   }
}

Solution 6 - C#

Use break in the inner loop.

Solution 7 - C#

You just want to break from the inner which would continue the outer.

while
{
   // outer loop

   while
   {
       // inner loop
       try
       {
           throw;
       }
       catch 
       {
           // how do I continue on the outer loop from here?
           break;
       }
   }
}

Solution 8 - C#

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:

while
{
   // outer loop

   while
   {
       // inner loop
       try
       {
           throw;
       }
       catch 
       {
           // break jumps to outer loop, ends inner loop immediately.
           break; //THIS IS THE BREAK
       }
   }
}

I believe that is what you were looking to be accomplished, correct? Thanks!

Solution 9 - C#

using System;

namespace Examples
{

    public class Continue : Exception { }
    public class Break : Exception { }

    public class NestedLoop
    {
        static public void ContinueOnParentLoopLevel()
        {
            while(true)
            try {
               // outer loop

               while(true)
               {
                   // inner loop

                   try
                   {
                       throw new Exception("Bali mu mamata");
                   }
                   catch (Exception)
                   {
                       // how do I continue on the outer loop from here?

                       throw new Continue();
                   }
               }
            } catch (Continue) {
                   continue;
            }
        } 
    }

}

}

Solution 10 - C#

Use an own exception type, e.g., MyException. Then:

while
{
   try {
   // outer loop
   while
   {
       // inner loop
       try
       {
           throw;
       }
       catch 
       {
           // how do I continue on the outer loop from here?
           throw MyException;
       }
   }
   } catch(MyException)
   { ; }
}

This will work for continuing and breaking out of several levels of nested while statements. Sorry for bad formatting ;)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSkunkSpinnerView Question on Stackoverflow
Solution 1 - C#Eric LippertView Answer on Stackoverflow
Solution 2 - C#ryansstackView Answer on Stackoverflow
Solution 3 - C#Jake PearsonView Answer on Stackoverflow
Solution 4 - C#WelbogView Answer on Stackoverflow
Solution 5 - C#shahkalpeshView Answer on Stackoverflow
Solution 6 - C#Marco MustapicView Answer on Stackoverflow
Solution 7 - C#David BasarabView Answer on Stackoverflow
Solution 8 - C#Maxim ZaslavskyView Answer on Stackoverflow
Solution 9 - C#elitsaView Answer on Stackoverflow
Solution 10 - C#zvrbaView Answer on Stackoverflow