简体   繁体   中英

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. It works great but sometimes when I leave the app running there will be an exception thrown like "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.

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.

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.

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