前两天看到Haissam推荐的一片文章——Exception Management in .NET.
确实是篇好文章,虽然有些年头了,但是仍颇有价值。仔细一看,原来是P&P出的一个Guide。
以下是一些我觉得有用的要点:
异常处理流程
-
exception handling process.
-
Processing of unhandled exceptions, see Figure 3.
异常检测
You should only catch exceptions when you need to specifically perform any of the following actions:
-
Gather information for logging
-
Add any relevant information to the exception
-
Execute cleanup code
-
Attempt to recover
异常传播
There are three main ways to propagate exceptions:
-
Let the exception propagate automatically:With this approach, you do nothing and deliberately ignore the exception.
-
Catch and rethrow the exception:With this approach, you catch and react to the exception, and clean up or perform any other required processing within the scope of the current method. If you cannot recover from the exception, you rethrow the same exception to your caller.
catch(TypeAException e)
{
// Code to do any processing needed.
// Rethrow the exception
throw;
}
-
Catch, wrap, and throw the wrapped exception:If you cannot recover, wrap the exception in a new exception, and throw the new exception back to the caller. The InnerException property of the Exception class explicitly allows you to preserve a previously caught exception. This allows the original exception to be wrapped as an inner exception inside a new and more relevant outer exception.
catch(TypeBException e)
{
// Code to do any processing needed.
// Wrap the current exception in a more relevant
// outer exception and rethrow the new exception.
throw(new TypeCException(strMessage, e));
}
When to use inner exception
You should wrap an exception only when wrapping an exception can provide a more relevant exception to the caller.
管理未处理异常
When an unhandled exception propagates to the last point or boundary at which your application can handle the exception before returning to the user, your application can no longer recover from the exception. At this point, it must gather information, log information, send any notifications, perform any cleanup, and do any other processing needed before managing the communication of the exception condition
to the user.
收集信息
What is the required information, just see table 2:
ps:文中关于Exception Hierarchies的部分有些过时了,现在的异常体系并没有严格遵守这种分类规则。