简体   繁体   English

C# 我应该循环直到没有异常吗?

[英]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.我想通过一个循环 go 一次,但前提是通过循环抛出异常 go 。 How would I write this in C#?我将如何在 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所以我正在使用这个简单的东西: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();
        });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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