建议65:总是处理未捕获的异常

来源:互联网 发布:数字软件下载 编辑:程序博客网 时间:2024/06/07 07:27

建议65:总是处理未捕获的异常

处理未捕获的异常是每个应用程序具备的基本功能,C#在APPDomain提供了UnhandledException事件来接收未捕获到的异常的通知。常见的应用如下:

复制代码
        static void Main(string[] args)        {            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);        }        static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)        {            Exception error = (Exception)e.ExceptionObject;            Console.WriteLine("MyHandler caught : " + error.Message);        }
复制代码

未捕获异常通常就是运行时期的Bug,我们可以在AppDomain.CurrentDomain.UnhandledException的注册事件方法CurrentDomain_UnhandledException中,将未捕获的异常信息记录在日志中。UnhandledException提供的机制并不能阻止应用程序终止,也就是说,执行CurrentDomain_UnhandledException方法后,应用程序就会终止。

 

在WinForm程序中使用ThreadException事件来处理UI线程异常,使用UnhandledException事件来处理非UI线程异常。ThreadException可以阻止应用程序终止。

 

 

 

 

转自:《编写高质量代码改善C#程序的157个建议》陆敏技

0 0
原创粉丝点击