WPF:我可以在哪里捕获应用程序崩溃事件?

时间:2018-03-26 17:17:25

标签: c# wpf exception-handling

我将此代码放在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();
        }
    }

并将此代码添加到button点击:

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

我的应用程序崩溃但没有参与此事件。

2 个答案:

答案 0 :(得分:1)

如果您在调试模式下运行,那么一旦遇到错误,您的应用就会中断。 你需要禁用它。按 Ctrl + Alt + E 以查看“异常”设置窗口并取消选中。记得把它转回去。

处理程序的完整列表: https://code.msdn.microsoft.com/windowsdesktop/Handling-Unhandled-47492d0b

您可以通过抛出一个来模拟错误。 https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/exceptions/creating-and-throwing-exceptions

答案 1 :(得分:1)

尝试在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);
}
相关问题