异常后如何继续执行?
How to continue execution after exceptions?
我正在使用 API 访问网站上的只读数据,例如交换,ticker/price。它工作得很好,但有时当我离开应用程序时 运行 会抛出异常,如 "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
}
}
}
我在评论中问你:
What are you trying to do? You want to try again in case of error?
你回答了:
@CodingYoshi yes basically, because this function is called in BG worker using a timer.
如果您使用定时器调用它,那么下面的代码就足够了,因为定时器会再次调用它:
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
循环。
我正在使用 API 访问网站上的只读数据,例如交换,ticker/price。它工作得很好,但有时当我离开应用程序时 运行 会抛出异常,如 "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
}
}
}
我在评论中问你:
What are you trying to do? You want to try again in case of error?
你回答了:
@CodingYoshi yes basically, because this function is called in BG worker using a timer.
如果您使用定时器调用它,那么下面的代码就足够了,因为定时器会再次调用它:
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
循环。