•使用 try-finally 并避免将 try-catch 用于清理代码。在书写规范的异常代码中,try-finally 远比 try-catch 更为常用。
•捕捉并再次引发异常时,首选使用空引发。这是保留异常调用堆栈的最佳方式。
•不要使用无参数 catch 块来处理不符合 CLS 的异常(不是从 System.Exception 派生的异常)。支持不是从 Exception 派生的异常的语言可以处理这些不符合 CLS 的异常。
5. 两种设计模式
5.1. Tester-Doer 模式
Doer 部分
public class Doer
{
public static void ProcessMessage(string message)
{
if (message == null)
{
throw new ArgumentNullException("message");
}
}
}
Tester部分
public class Tester
{
public static void TesterDoer(ICollection<string> messages)
{
foreach (string message in messages)
{
if (message != null)
{
Doer.ProcessMessage(message);
}
}
}
}
5.2. TryParse 模式
TryParse 方法类似于 Parse 方法,不同之处在于 TryParse 方法在转换失败时不引发异常。
Parse方法
public void Do()
{
string s = “a”;
double d;
try
{
d = Double.Parse(s);
}
catch (Exception ex)
{
d = 0;
}
}
TryParse方法
public void TryDo()
{
string s = "a";
double d;
if (double.TryParse(s, out d) == false)
{
d = 0;
}
}
6. 微软企业库异常处理模块
6.1. 创建自定义异常包装类
public class BusinessLayerException : ApplicationException
{
public BusinessLayerException() : base()
{
}
public BusinessLayerException(string message) : base(message)
{
}
public BusinessLayerException(string message, Exception exception) :
base(message, exception)
{
}
protected BusinessLayerException(SerializationInfo info, StreamingContext context) :
base(info, context)
{
}
}
6.2. 配置异常处理
<add name="Wrap Policy">
<exceptionTypes>
<add type="System.Data.DBConcurrencyException, System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
postHandlingAction="ThrowNewException" name="DBConcurrencyException">
<exceptionHandlers>
<add exceptionMessage="Wrapped Exception: A recoverable error occurred while attempting to access the database."
exceptionMessageResourceType="" wrapExceptionType="ExceptionHandlingQuickStart.BusinessLayer.BusinessLayerException, ExceptionHandlingQuickStart.BusinessLayer"
type="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.WrapHandler, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling, Version=3.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
name="Wrap Handler" />
</exceptionHandlers>
</add>
</exceptionTypes>
</add>










