【问题标题】:WPF: where i can catch application crash event?WPF:我可以在哪里捕获应用程序崩溃事件?
【发布时间】:2018-09-04 22:19:27
【问题描述】:

我把这段代码放在我的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;

我的应用程序崩溃了,但没有进入这个事件。

【问题讨论】:

标签: c# wpf exception-handling


【解决方案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);
}

【讨论】:

  • 好的,现在可以了,我还需要添加 UnhandledExceptionEventArgs 或 DispatcherUnhandledExceptionEventArgs 就足够了?
  • UnhandledExceptionEventArgs 处理所有未处理的异常,DispatcherUnhandledExceptionEventArgs 包含!抱歉回复晚了
  • 那么 UnhandledExceptionEventArgs 就够了,不需要 DispatcherUnhandledExceptionEventArgs 了?
  • DispatcherUnhandledException 捕获 UI 线程上的所有异常。在使用它时,您可以调用DispatcherUnhandledExceptionEventArgsUnhandledExceptionEventArgs,其中包括所有线程上的前者和所有其他未处理的异常。
【解决方案2】:

如果您在调试模式下运行,那么一旦您遇到错误,您的应用就会中断。 你需要禁用它。按 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-05-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-01
    • 2018-03-13
    相关资源
    最近更新 更多