处理程序中没有被try-catch捕获的异常,避免程序异常退出(或者在退出之前记录日志信息)。
using System;
using System.Threading;
using System.Windows.Forms;
namespace CatchUnhandledException
{
internal static class Program
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
Application.ThreadException += new ThreadExceptionEventHandler(Form1.UIThreadExceptionHander);
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);// 这一步需要在实例化主窗口之前
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);// 此举并不能阻止应用程序退出
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
/// <summary>
/// 处理非UI线程引发的未处理异常
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
try
{
Exception ex = e.ExceptionObject as Exception;
MessageBox.Show($"{ex.Message}\r\n详情:\r\n{ex.StackTrace}", "非UI线程引发的未处理异常");
}
catch (Exception exc)
{
try
{
MessageBox.Show($"在处理非UI线程引发的未处理异常时出现致命错误:{exc.Message}");
}
finally
{
Application.Exit();
}
}
}
}
}
using System;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace CatchUnhandledException
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
/// <summary>
/// 捕获未处理的UI线程异常
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public static void UIThreadExceptionHander(object sender, ThreadExceptionEventArgs t)
{
try
{
Exception ex = t.Exception;
MessageBox.Show($"{ex.Message}\r\n详情:\r\n{ex.StackTrace}", "UI线程中的未处理异常");
}
catch (Exception exc)
{
try
{
MessageBox.Show($"在处理UI线程中的未处理异常时出现致命错误:{exc.Message}\r\n详情:\r\n{exc.StackTrace}");
}
finally
{
Application.Exit();
}
}
}
private void btnUIException_Click(object sender, EventArgs e)
{
throw new Exception("UI线程异常");
}
private void btnNonUIException_Click(object sender, EventArgs e)
{
Thread thread = new Thread(() => { throw new Exception("非UI线程异常"); });
thread.Start();
}
}
}