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.

Dim Mark
  • 73
  • 2
  • 8

2 Answers2

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);
}
Outman
  • 3,100
  • 2
  • 15
  • 26
  • Ok this works now, i need also to add UnhandledExceptionEventArgs or DispatcherUnhandledExceptionEventArgs is enough ? – Dim Mark Mar 26 '18 at 18:09
  • `UnhandledExceptionEventArgs` takes care of all unhandled exceptions, `DispatcherUnhandledExceptionEventArgs` **included**! sorry for the late reply – Outman Mar 27 '18 at 02:23
  • So UnhandledExceptionEventArgs in enough and no need DispatcherUnhandledExceptionEventArgs ? – Dim Mark Mar 27 '18 at 08: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 '18 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

Developer Guy
  • 2,318
  • 6
  • 19
  • 37
Andy
  • 11,864
  • 2
  • 17
  • 20