In this code sample, is there any way to continue on the outer loop from the catch block?
while
{
// outer loop
while
{
// inner loop
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?)
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;
}
}
}
}
}
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 ;)
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'.