2

I put this code in my entry point:

   public partial class App : Application
    {
        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);
            Dispatcher.UnhandledException += Dispatcher_UnhandledException;
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;

        }

        private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            throw new NotImplementedException();
        }

        private void Dispatcher_UnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
        {
            throw new NotImplementedException();
        }
    }

And add this code into some button click:

int num = 10;
int t = 5;
t = t - 5;
int error = num / t;

And my application crash but not go into this events.

4

2 Answers 2

10

Try adding this code in App.xaml.cs

public App() : base() {
    this.Dispatcher.UnhandledException += OnDispatcherUnhandledException;
}

void OnDispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e) {
    MessageBox.Show("Unhandled exception occurred: \n" + e.Exception.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
}
4
  • Ok this works now, i need also to add UnhandledExceptionEventArgs or DispatcherUnhandledExceptionEventArgs is enough ?
    – Dim Mark
    Mar 26, 2018 at 18:09
  • UnhandledExceptionEventArgs takes care of all unhandled exceptions, DispatcherUnhandledExceptionEventArgs included! sorry for the late reply
    – Outman
    Mar 27, 2018 at 2:23
  • So UnhandledExceptionEventArgs in enough and no need DispatcherUnhandledExceptionEventArgs ?
    – Dim Mark
    Mar 27, 2018 at 8:32
  • DispatcherUnhandledException catches all exceptions on the UI thread. while using it you can call either DispatcherUnhandledExceptionEventArgs or UnhandledExceptionEventArgs which includes the former and every other unhandled exception on all threads.
    – Outman
    Mar 27, 2018 at 15:00
1

If you run in debug mode then your app will break as soon as you hit an error. You would need to disable that. Press Ctrl+Alt+E to see the Exception settings window and uncheck some. Remember to turn it back though.

The full list of handlers: https://code.msdn.microsoft.com/windowsdesktop/Handling-Unhandled-47492d0b

You can simulate an error just by throwing one. https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/exceptions/creating-and-throwing-exceptions

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.