Reputation: 330912
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?
Upvotes: 1
Views: 1959
Reputation: 27009
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.
Upvotes: 2
Reputation: 2496
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
}
}
}
Upvotes: 3