开发者

C# Should I Loop until no exception?

开发者 https://www.devze.com 2022-12-09 15:00 出处:网络
I want to go once through a loop but only if an exception is thrown go back th开发者_StackOverflow中文版rough the loop. How would I write this in C#?

I want to go once through a loop but only if an exception is thrown go back th开发者_StackOverflow中文版rough 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();
}


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();
        });
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号