简介
异常处理应用程序块。由Microsoft提供一个标准的框架,而不是不治本的方法纳入您的应用程序异常处理应用程序块。本文总结了相同的基本概念和用法。
概念异常处理过程异常的东西时,异常是由您的代码
检测
异常日志
记录异常的过程,其中可能包括发送格式化异常事件日志或发送电子邮件
异常政策
允许你控制异常处理和日志记录到您的代码中使用外部配置文件,而不是烘烤等规则的行为
使用异常处理块
3事情可以做,当你发现一个异常:
你可以用在一个新的异常的异常,添加新的上下文信息或细节。原始的异常仍然可以通过InnerException属性时,新的异常传播到调用堆栈。
您可以用一个新的异常异常。这样做时,你不想原始异常的详细信息,跨应用程序边界传播。
您可以登录异常。您可以在组合包装或更换异常,或者您可以登录原始的异常并调用堆栈向上传播原有的或新的异常。
编码待办事项:
添加引用:
新增配置项的app.config低于LT; configSectionsgt;根LT下configurationgt;;元素的元素:{C}用于记录,LT; configSectionsgt;元素添加以下几节:
Microsoft.Practices.EnterpriseLibrary.Common.dll
Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.dll
Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging.dll
添加LT; exceptionHandlinggt;直接下的根元素LT元素; configurationgt,你在里面添加例外政策:
<section
name=锟loggingConfiguration锟?type=锟Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.LoggingSettings,
Microsoft.Practices.EnterpriseLibrary.Logging锟?/>
或者,您可以添加元素容易使用Enterprise Library配置工具(Visual Studio 2005中的一部分),如下所示:{S0}
<exceptionHandling>
<exceptionPolicies>
// Add policy name: see ppt for code sample
<exceptionTypes>
// Add exception type: see ppt for code sample
<exceptionHandlers>
// Add handlers: see ppt for code sample
</exceptionHandlers>
// Close add tag:
</exceptionTypes>
// Close add tag:
</exceptionPolicies>
</exceptionHandling>
导入命名空间异常处理块Microsoft.Practices.EnterpriseLibrary.ExceptionHandling在您的项目中,对上述命名空间中的类编写代码。使用ExceptionPolicy类概述类暴露了一个静态方法:HandleException(),让客户端应用程序进行交互的异常处理块
。您作为一个参数供应政策; HandleException方法使用一个工厂来创建对象类型提供政策ExceptionPolicyImpl;这个对象有一个ExceptionPolicyEntry对象的集合命名的策略配置文件中指定的每个异常类型的一个对象;??每个ExceptionPolicyEntry异常类型,包含实现的IExceptionHandler接口的对象的集合;有序集合,并提供异常处理块使用在执行政策时的顺序,其中的每个对象有相关的配置信息,具体到每种类型的处理程序。例如:
按钮单击事件处理程序与简单的异常处理(C#)的例子
日志按钮单击事件处理程序示例(C#)
private void btn_Click(object sender, EventArgs e)
{
try
{
throw new Exception(锟This is a test exception锟?;
}
catch (Exception ex)
{
bool rethrow = ExceptionPolicy.HandleException(ex, 锟Global Policy锟?;
if(rethrow)
{
throw;
}
}
}
样本记录的app.config配置信息显示在所附的PPT。参考文献... ...{A}{A2}
// The catch block invokes ExceptionPolicy.HandleException method by passing the exception object (ex)
// as well as the policy (锟Log Only Policy锟? as arguments
private void btn_Click(object sender, EventArgs e)
{
try
{
throw new Exception(锟This is a test exception锟?;
}
catch (Exception ex)
{
bool rethrow = ExceptionPolicy.HandleException(ex, 锟Log Only Policy锟?;
if(rethrow)
{
throw;
}
}
}