以下操作在Program.cs中
1.最简单的方式try...catch..
一般用在某一段容易出错的代码,如果用在整个软件排查,如下所示
static void Main()
{
try
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new FrmMain());
}
catch (Exception ex)
{
MessageBox.Show(string.Format("捕获到未处理的异常:{0}\n异常信息:{1}\n异常堆栈:{2}", ex.GetType(), ex.Message, ex.StackTrace));
}
}
2.上面的方法并不是很好的方式,下面这种更好一些。
主线程事件监听:Application.ThreadException,程序并不会因为异常而退出。
子线程异常捕获AppDomain.CurrentDomain.UnhandledException
static void Main()
{
Application.ThreadException += Application_ThreadException;
AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new FrmMain());
}
static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
Exception ex = e.ExceptionObject as Exception;
MessageBox.Show(string.Format("捕获到未处理异常:{0}\n异常信息:{1}\n异常堆栈:{2}\r\nCLR即将退出:{3}", ex.GetType(), ex.Message, ex.StackTrace, e.IsTerminating));
}
static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
{
Exception ex = e.Exception;
MessageBox.Show(string.Format("捕获到未处理异常:{0}\n异常信息:{1}\n异常堆栈:{2}", ex.GetType(), ex.Message, ex.StackTrace));
}