我有一个代码段,负责编排几个模块的执行,它对错误非常敏感--我想确保记录并警告发生的每一个异常。
现在我有这样的事情:
try
{
ModuleAResult aResult = ModuleA.DoSomethingA();
}
catch (Exception ex)
{
string errorMessage = string.Format("Module A failed doing it's thing. Specific exception: {0}", ex.Message);
// Log exception, send alerts, etc.
}
try
{
ModuleBResult bResult = ModuleB.DoSomethingB();
}
catch (Exception ex)
{
string errorMessage = string.Format("Module B failed doing it's thing. Specific exception: {0}", ex.Message);
// Log exception, send alerts, etc.
}
// etc for other modules.在我看来,多重尝试捕获使得这个片段的可读性降低。这样做真的对吗?
发布于 2014-03-18 08:44:44
你做得很好。
这样,您可以在每个模块之后处理错误。如果您想全部运行,然后执行错误处理,请考虑以下备选方案:
try
{
ModuleAResult aResult = ModuleA.DoSomethingA();
ModuleBResult bResult = ModuleB.DoSomethingB();
}
catch(ModuleAException ex)
{
// handle specific error
}
catch(ModuleBException ex)
{
// handle other specific error
}
catch (Exception ex)
{
// handle all other errors, do logging, etc.
}发布于 2014-03-18 08:46:11
是的,这是正确的。
但是您应该考虑到性能,也许最好将所有方法调用放在一次尝试/捕捉中,并在方法本身的异常中添加堆栈跟踪和错误信息。
public void ModuleA.DoSomethingA()
{
throw new Exception("Error in module A");
}
try
{
ModuleAResult aResult = ModuleA.DoSomethingA();
ModuleBResult bResult = ModuleB.DoSomethingB();
}
catch (Exception ex)
{
// get information about exception in the error message
}发布于 2014-03-18 08:50:05
我认为这取决于你想要遵循的方法。
似乎您的错误消息对于每个引发异常的模块是不同的,所以我想您遵循的方法是正确的。
您本可以将整个事件放在一个大的尝试-捕捉块中,那么在打印泛型过度时,您将不知道是哪个模块导致了异常。
try
{
ModuleAResult aResult = ModuleA.DoSomethingA();
ModuleBResult bResult = ModuleB.DoSomethingB();
}
catch (Exception ex)
{
string errorMessage = string.Format("Either Module A or B failed", ex.Message);
// Log exception, send alerts, etc.
}因此,如果您希望您的异常处理不干净,请使用上面的代码。否则,你所遵循的是绝对好的。
https://stackoverflow.com/questions/22474112
复制相似问题