【发布时间】:2012-01-17 04:01:07
【问题描述】:
是否有任何理由更喜欢其中一种在 Windows 窗体应用程序中实现全局异常处理程序的方法?
第一种方法
static void Main(string[] args)
{
try
{
System.Windows.Forms.Application.Run(mainform);
}
catch (Exception ex)
{
// Log error and display error message
}
}
第二种方法
static void Main(string[] args)
{
System.Windows.Forms.Application.ThreadException +=
new ThreadExceptionEventHandler(Application_ThreadException);
System.Windows.Forms.Application.Run(mainform);
}
static void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
{
// Log error and display error message
}
处理 ThreadException 事件是否会给你一些 try / catch 没有的东西?
【问题讨论】:
-
第一种方法甚至不能在发布模式下工作,即当你运行你的 exe 时,这将是一个未处理的异常,你将不会到达 catch 块;仅在使用 Visual Studio 时有效。试试看,在主窗体中放置一个按钮并在那里抛出异常。
标签: c# winforms exception-handling