winform或wpf中全局异常捕获

winform或者wpf项目中难免会遇到忘记捕获的异常的代码块,c#为我们提供了全局捕获异常的机制

winform中在Program.cs中这样写

   static class Program
   {      
[STAThread]
static void Main() {
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
//UI线程异常 Application.ThreadException += Application_ThreadException; //非UI线程异常 AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;

Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(
false); Application.Run(new FormMain());
}
private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) { //Log.Error or MessageBox.Show } private static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e) { //Log.Error or MessageBox.Show } }

wpf中在App.xaml.cs这样写

    public partial class App : Application
    {
        public App()
        { 
            //UI线程异常
            this.DispatcherUnhandledException += App_DispatcherUnhandledException;
            //非UI线程异常
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
        }
        private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            //Log.Error or MessageBox.Show
        }
        private void App_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
        {
            //Log.Error or MessageBox.Show
        }
     }

我们可以在异常回调里面弹窗提示或者记录日志

这样写可以捕获大部分异常信息,但是有些应用场景例外

比如我们使用[DllImport("xxx.dll")]调用c\c++写的方法时,无法捕获异常导致程序卡死或者闪退

我们可以尝试用[HandleProcessCorruptedStateExceptions]特性

[HandleProcessCorruptedStateExceptions]
public void DoSomething()
{
      try
      {
          Test(1, 2);
      }
      catch(Exception ex)
      {
         //Log or MessageBox.Show
      }
}
[DllImport("xxx.dll")]
public static extern int Test(int a,int b);

 

posted on 2020-04-22 09:14  杂酱面  阅读(908)  评论(0编辑  收藏  举报