简体   繁体   English

异常后如何继续执行?

[英]How to continue execution after exceptions?

I am using an API that accesses read only data on a website like an exchange, for ticker/price. 我正在使用一个API,用于访问股票市场(如交易所)的只读数据,以获取报价/价格。 It works great but sometimes when I leave the app running there will be an exception thrown like "TaskCanceledException". 它工作得很好,但是有时当我让应用程序运行时,会抛出类似“ TaskCanceledException”的异常。

How can I safely ignore these and continue executing the same function? 如何安全地忽略这些并继续执行相同的功能?

Because if the function call fails, nothing bad happens, as I am just showing prices so it could skip a few function calls without any issues for the user. 因为如果函数调用失败,则不会发生任何不好的事情,因为我只是在显示价格,因此它可以跳过一些函数调用而不会给用户带来任何问题。

Do I have to do something like this? 我需要做这样的事情吗?

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

and so on for every exception occurrence? 等等,对于每个异常情况?

I believe the wiser approach would be to catch the exception within the UpdateFields function. 我相信更明智的方法是在UpdateFields函数中捕获异常。

I assume that function iterates through each field, updating as it goes, and within that loop would be where it should be caught. 我假设函数在每个字段中进行迭代,并随其更新,并且在该循环中将捕获该字段。

    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
            }

        }
    }

I asked you in a comment: 我在评论中问你:

What are you trying to do? 你想做什么? You want to try again in case of error? 您想在出错的情况下重试吗?

And you answered: 你回答:

@CodingYoshi yes basically, because this function is called in BG worker using a timer. @CodingYoshi基本上是,因为在BG worker中使用计时器调用了此函数。

If you are calling this using a timer, then just the code below will be enough because the timer will call it again: 如果您使用计时器来调用它,那么只需下面的代码就足够了,因为计时器会再次调用它:

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

If you are not using a timer but you want to keep trying, you can do so in a loop like this: 如果您没有使用计时器,但想继续尝试,则可以在如下循环中进行:

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

Change the while loop to a for loop if you want to try x number of times and then give up. 如果要尝试x次然后放弃,则将while循环更改for循环。

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

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