Continue in nested while loops

后端 未结 10 1548
名媛妹妹
名媛妹妹 2020-12-07 14:26

In this code sample, is there any way to continue on the outer loop from the catch block?

while
{
   // outer loop

   while
   {
       // inner loop
               


        
相关标签:
10条回答
  • 2020-12-07 15:27
        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?)

    0 讨论(0)
  • 2020-12-07 15:27
    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;
                }
            } 
        }
    
    }
    
    }
    
    0 讨论(0)
  • 2020-12-07 15:29

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

    0 讨论(0)
  • 2020-12-07 15:31

    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'.

    0 讨论(0)
提交回复
热议问题