WPF global exception handler

This question already has an answer here:

  • Globally catch exceptions in a WPF application? 6 answers

  • You can handle the AppDomain.UnhandledException event

    EDIT: actually, this event is probably more adequate: Application.DispatcherUnhandledException


    You can trap unhandled exceptions at different levels:

  • AppDomain.CurrentDomain.UnhandledException From all threads in the AppDomain.
  • Dispatcher.UnhandledException From a single specific UI dispatcher thread.
  • Application.Current.DispatcherUnhandledException From the main UI dispatcher thread in your WPF application.
  • TaskScheduler.UnobservedTaskException from within each AppDomain that uses a task scheduler for asynchronous operations.
  • You should consider what level you need to trap unhandled exceptions at.

    Deciding between #2 and #3 depends upon whether you're using more than one WPF thread. This is quite an exotic situation and if you're unsure whether you are or not, then it's most likely that you're not.


    A quick example of code for Application.Dispatcher.UnhandledException:

        public App() :base() {
            this.Dispatcher.UnhandledException += OnDispatcherUnhandledException;
        }
    
        void OnDispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e) {
            string errorMessage = string.Format("An unhandled exception occurred: {0}", e.Exception.Message);
            MessageBox.Show(errorMessage, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            e.Handled = true;
        }
    

    I added this code in App.xaml.cs

    链接地址: http://www.djcxy.com/p/5942.html

    上一篇: 如何从文件内容创建Java字符串?

    下一篇: WPF全局异常处理程序