• 【转】编写高质量代码改善C#程序的157个建议——建议65:总是处理未捕获的异常


    建议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个建议》陆敏技

  • 相关阅读:
    第一章 新手入门
    Excle生成T层加工ODS层存储过程
    Excel生成建表角本
    数据仓库建模技巧
    算法第四章作业
    删数问题
    算法第三章作业
    第三章上机实践报告
    第二章作业
    Thinkphp6框架学习:($this->error()undefined)Call to undefined method appindexcontrollerAdmin::error()
  • 原文地址:https://www.cnblogs.com/farmer-y/p/7992823.html
Copyright © 2020-2023  润新知