假设我们有一个我们使用的外部服务器(例如电话站等)。我们还有下一个代码:
try
{
externalService.CreateCall(callParams);
}
catch (Exception ex)
{
_log.Error("Unexpected exception when trying execute an external code.", ex);
_callService.UpdateCallState(call, CallState.Disconnected, CallOutcome.Failed);
throw;
}
Run Code Online (Sandbox Code Playgroud)
理论上UpdateCallState可以抛出,但我们会使用该代码隐藏这个异常,并且只处理CreateCall以正确方式生成的异常。
问题是,对于这些情况,正确的模式是什么,以便我们正确对待所有异常?
你总是可以try..catch在第一个捕获物内嵌套另一个并适当地处理它。
try
{
externalService.CreateCall(callParams);
}
catch (Exception ex)
{
_log.Error("Unexpected exception when trying execute an external code.", ex);
try
{
_callService.UpdateCallState(call, CallState.Disconnected, CallOutcome.Failed);
}
catch(Exception updateEx)
{
// do something here, don't just swallow the exception
}
throw; // this still rethrows the original exception
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1953 次 |
| 最近记录: |