繁体   English   中英

异常后如何继续执行?

[英]How to continue execution after exceptions?

我正在使用一个API,用于访问股票市场(如交易所)的只读数据,以获取报价/价格。 它工作得很好,但是有时当我让应用程序运行时,会抛出类似“ TaskCanceledException”的异常。

如何安全地忽略这些并继续执行相同的功能?

因为如果函数调用失败,则不会发生任何不好的事情,因为我只是在显示价格,因此它可以跳过一些函数调用而不会给用户带来任何问题。

我需要做这样的事情吗?

try
{
    this.UpdateFields ( );
}
catch ( Exception ex )
{
    Console.WriteLine ( ex );
    Console.WriteLine ( "Continue" );
    this.UpdateFields ( );
}

等等,对于每个异常情况?

我相信更明智的方法是在UpdateFields函数中捕获异常。

我假设函数在每个字段中进行迭代,并随其更新,并且在该循环中将捕获该字段。

    private void UpdateFields()
    {

        foreach (var field in fields)
        {
            try
            {
                // Update a field
            }
            catch (TaskCanceledException ex)
            {
                Console.WriteLine(ex);
                // Control flow automatically continues to next iteration
            }

        }
    }

我在评论中问你:

你想做什么? 您想在出错的情况下重试吗?

你回答:

@CodingYoshi基本上是,因为在BG worker中使用计时器调用了此函数。

如果您使用计时器来调用它,那么只需下面的代码就足够了,因为计时器会再次调用它:

try
{
    this.UpdateFields();
}
catch (Exception e)
{
    // Either log the error or do something with the error
}

如果您没有使用计时器,但想继续尝试,则可以在如下循环中进行:

bool keepTrying = true;
while (keepTrying)
{
    try
    {
        this.UpdateFields();
    }
    catch (Exception e)
    {
        // Either log the error or set keepTrying = false to stop trying
    }
}

如果要尝试x次然后放弃,则将while循环更改for循环。

暂无
暂无

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

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