简体   繁体   中英

C# Should I Loop until no exception?

I want to go once through a loop but only if an exception is thrown go back through the loop. How would I write this in C#?

Thanks

This smells of bad design to me. The general rule is: exceptions should not be used for flow control. There are a number of reasons for this; namely, there are usually better/more reliable methods that can be used to check things before an exceptions is thrown, and also it decreases efficiency.

Nonetheless, just for the sake of argument, you could do something like the following:

while (true)
{
    try
    {
        // do stuff here
    }
    catch (MyException)
    {
        continue;
    }

    // all is good
    break;
}

Again - this is not the recommended way. I would be happy to suggest something better if you could provide a bit more context/examples/

What about the following where you can set a retry count:

            int tryCount = 0;

            while (tryCount < 3)
            {
                try
                {
                    someReturn = SomeFunction(someParams);
                }
                catch (Exception)
                {
                    tryCount++; 
                    continue;
                }
                break; 
            }

That really depends on what you're doing, and the type of exception being thrown. Many exceptions aren't something that would be fixed by just trying again with the exact same inputs/data, and thus looping would just keep generating the exception ad infinitum.

Instead, you should check for relevant exceptions and then handle them in an appropriate manner for those particular exceptions.

Why not call a function that actually does the loop, and have a catch after it that would call the function again.

private void loop() {
  for(...) {
  }
}

some other method:

try {
  loop();
} catch(Exception e) {
  loop();
}

Seems like a bad idea but anyway try something like this :

DELETED

Something like:

bool done = false;
while( ! done )
{
  try
  {
    DoSomething();
    done = true;
  } catch(Exception ex)
  {
    HandleException(ex);
  }
}

As Noldorin said, it smells like a bad design. You're using exceptions to control the flow of the program. Better to have explicit checks for the conditions that will cause you to repeat the operation.

So I am using this simple stuff :D

bool exceptionthrow = false;

        while (!exceptionthrow)
        {
            try
            {
                value = Convert.ToInt32(Console.ReadLine()); //example
                exceptionthrow = true;
            }
            catch (Exception)
            {
                exceptionthrow = false;
                continue;
            }
        }

Hope it helps :)

You could use Polly

and then you just need to configure the Policy with your exceptions and retry count:

var retryPolicy = Policy
                .Handle<IOException>(x => x.Message.Contains("already exist"))
                .Or<FormatException>()
                .Retry(3);

and you use like this:

retryPolicy.Execute(() =>
        {
            throw new FormatException();
        });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM