[英]Prevent Winform to crash on unhandled exception
我試圖通過這種方式捕獲未處理的異常:
static class Program
{
[STAThread]
static void Main(string[] args)
{
Application.ThreadException += new ThreadExceptionEventHandler(Program.ThreadExceptionEventHandler);
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(Program.UnhandledExceptionEvent);
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
public static void UnhandledExceptionEvent(Object sender, UnhandledExceptionEventArgs e)
{
MessageBox.Show("UnhandledExceptionEvent", "UnhandledExceptionEvent");
}
public static void ThreadExceptionEventHandler(Object sender, ThreadExceptionEventArgs e)
{
MessageBox.Show(e.Exception.Message, "ThreadExceptionEventHandler");
}
}
private void button1_Click(object sender, EventArgs e)
{
//Execute method on a new thread
new Thread(delegate()
{
//Do stuff ...
throw new Exception("Some random unhandled exception");
}).Start();
}
異常被UnhandledExceptionEventHandler捕獲,我可以看到彈出的消息框,但應用程序仍然崩潰說“程序已停止工作”。
如何在發生異常后保持應用程序運行?
有關捕獲未處理的excpetions的信息,請參閱此stackoverflow問題 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.