考虑到吃异常总是很糟糕,重新抛出异常会丢失调用堆栈,那么重构以下代码的正确方法是什么呢?
饮食异常:
try
{
… do something meaningful
}
catch(SomeException ex)
{
// eat exception
}发布于 2010-10-08 01:48:27
try
{
...
}
catch(SomeException e)
{
//Do whatever is needed with e
throw; //This rethrows and preserves call stack.
}发布于 2010-10-08 01:52:47
捕获和处理特定类型的异常。好的做法是捕获而不是,只捕获System.Exception即可。一个健壮的例程将强烈地键入它知道如何处理的异常。
异常不应该用于控制流,但通常需要根据异常的类型执行特定的展开过程。
根据具体的类型,您可能会选择重新抛出它,也可能不会。例如,向使用导致异常的代码的错误页抛出ASP分析异常将导致无限循环。
try
{
}
catch( FileIOException )
{
// unwind and re-throw as determined by the specific exception type
}
catch( UnauthorizedAccessException )
{
// unwind and re-throw as determined by the specific exception type
}
catch( SomeOtherException )
{
// unwind and re-throw as determined by the specific exception type
}
catch( Exception )
{
// log and re-throw...add your own message, capture the call stack, etc.
// throw original exception
throw;
// OR, throw your own custom exception that provides more specific detail and captures
// the original exception as the inner exception
throw new MyStronglyTypedException();
}
finally
{
// always clean up
}发布于 2010-10-08 05:02:52
大多数人认为吃掉/抑制异常是完全不好的,特别是对于所有的异常。(具有讽刺意味的是,他们使用catch all响应“不要使用catch-all,它是邪恶的”:-)。我不理解人们对这种观点的宗教狂热,因为如果明智地使用,这种方法没有什么错。
- If a programmer forgets to document one exception they might throw, I won't know I need to catch it, and my code will have a vulnerability I'm not aware of.
- If someone updates a method so that it throws a new exception type, that new exception could ripple up the call stack until it hits my code. But my code was not built to handle the exception. Don't tell me that the libraries I'm calling will never change.
- Every exception type you specifically handle is another code path to be tested. It significantly multiplies the complexity of testing and/or the risks that a broken bit of handling code might go unnoticed.
默默地吃/抑制异常的诀窍就是确保这是正确的处理方法。(在许多情况下,情况并非如此)。所以可能没有必要重构你的示例代码--它可能不是一个糟糕的juju。
https://stackoverflow.com/questions/3884328
复制相似问题