在c#开发winform或者wpf的时候,有时候程序存在未处理的异常导致程序崩溃,这时需要全局异常捕获来防止程序崩溃和捕捉异常原因;下面贴上wpf全局异常捕获和winform全局异常捕获代码,希望对大家有用。
WINFORM
winform程序在program.cs文件中加入如下代码.
[STAThread]
private static void Main()
{
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
//处理UI线程异常
Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
//处理非UI线程异常
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new FrmMain());
}
private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
try
{
string str = GetExceptionMsg(e.ExceptionObject as Exception, e.ToString());
}
catch { }
}
private static void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
{
try
{
string str = GetExceptionMsg(e.Exception, e.ToString());
}
catch { }
}
/// <summary>
/// 生成自定义异常消息
/// </summary>
/// <param name="ex">异常对象</param>
/// <param name="backStr">备用异常消息:当ex为null时有效</param>
/// <returns>异常字符串文本</returns>
private static string GetExceptionMsg(Exception ex, string backStr)
{
try
{
StringBuilder sb = new StringBuilder();
sb.AppendLine("****************************异常文本****************************");
sb.AppendLine("【出现时间】:" + DateTime.Now.ToString());
if (ex != null)
{
sb.AppendLine("【异常类型】:" + ex.GetType().Name);
sb.AppendLine("【异常信息】:" + ex.Message);
//sb.AppendLine("【堆栈调用】:" + ex.StackTrace);
}
else
{
sb.AppendLine("【未处理异常】:" + backStr);
}
sb.AppendLine("****************************************************************");
return sb.ToString();
}
catch { return "程序异常!"; }
}
WPF
wpf在app.xaml文件中分别加入如下代码.
//App.xaml前台代码
DispatcherUnhandledException="Application_DispatcherUnhandledException"
//App.xaml后台代码
private void Application_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
{
//记录日志
}