Hit*_*mer 3 c# exception-handling
我刚刚继承了有超过300个代码的代码:
catch(Exception ex)
{
string s = ex.Message ;
}
Run Code Online (Sandbox Code Playgroud)
下次我遇到写这篇文章的人时,我该怎么办呢?
不过实话说...
这显然是编码恐怖,是程序员可以做的最糟糕的事情之一.我是否应该通过并删除所有这些并查看运行应用程序时的真实情况?你怎么会纠正这个错误?
这是一个WinForms应用程序,由我的组织内部运行约24个用户.
您可以删除所有这些catch块,并在启动第一个表单之前添加以下代码:
public static void Main(string[] args)
{
// Event handler for handling UI thread exceptions.
Application.ThreadException +=
new ThreadExceptionEventHandler(App_UiThreadException);
// Force all Windows Forms errors to go through our handler.
// NB In .NET 4, this doesn't apply when the process state is corrupted.
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
// Event handler for handling non-UI thread exceptions.
AppDomain.CurrentDomain.UnhandledException += new
UnhandledExceptionEventHandler(App_NonUiThreadException);
// Run the application.
}
Run Code Online (Sandbox Code Playgroud)
拦截所有事件
调用SetUnhandledExceptionMode可确保无论应用程序配置设置如何都将拦截所有未处理的异常.
请注意,从.NET Framework 4开始,上面编写并在下面讨论的事件不会针对损坏进程状态的异常(例如堆栈溢出或访问冲突)引发 - 除非事件处理程序是安全关键的并且具有HandleProcessCorruptedStateExceptionsAttribute属性.
关于破坏流程状态的异常,有一个有趣的博客条目.
UI线程异常
处理Application.ThreadException事件在ui线程上截获未处理的异常.在您的过滤器代码中,您可以记录每个异常.如果要复制ui线程异常的现有行为,您应该能够吞下大部分内容.
非UI线程异常
处理AppDomain.UnhandledException事件会截获非ui线程上的未处理异常.在您的过滤器代码中,您可以记录每个异常.不幸的是,大多数非ui线程异常在触发此事件时已经是致命的,因此不可能通过执行此操作来复制非ui线程异常的现有行为.