未处理的异常

1.控制台应用程序全局捕获未处理的异常

1         static void Main(string[] args)
2         {
3             AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
4         }

2.Winform应用程序全局捕获未处理的异常

 1 public static void Main(string[] args)
 2 {
 3     // Add the event handler for handling UI thread exceptions to the event.
 4     Application.ThreadException += new ThreadExceptionEventHandler(ErrorHandlerForm.Form1_UIThreadException);
 5 
 6     // Set the unhandled exception mode to force all Windows Forms errors to go through
 7     // our handler.
 8     Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
 9 
10     // Add the event handler for handling non-UI thread exceptions to the event. 
11     AppDomain.CurrentDomain.UnhandledException +=
12         new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
13 
14     // Runs the application.
15     Application.Run(new ErrorHandlerForm());
16 }

3.WPF应用程序全局捕获未处理的异常

 1     /// <summary>
 2     /// Interaction logic for App.xaml
 3     /// </summary>
 4     public partial class App : Application
 5     {
 6         private void App_OnStartup(object sender, StartupEventArgs e)
 7         {
 8             AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
 9 
10             Application.Current.DispatcherUnhandledException += Current_DispatcherUnhandledException;
11         }
12 
13         void Current_DispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
14         {
15             throw new NotImplementedException();
16         }
17 
18         void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
19         {
20             throw new NotImplementedException();
21         }
22     }

但是AppDomain.CurrentDomain.UnhandledException并非像声明的那样能捕获到所有的异常,详细请参与如下文档。

http://stackoverflow.com/questions/19164556/how-to-catch-observe-an-unhandled-exception-thrown-from-a-task

http://blogs.msdn.com/b/pfxteam/archive/2009/05/31/9674669.aspx

原文地址:https://www.cnblogs.com/JustYong/p/5114054.html