【问题标题】:Unhandled exception handler won't work in VS 2019未处理的异常处理程序在 VS 2019 中不起作用
【发布时间】:2026-01-29 23:00:01
【问题描述】:

我正在尝试为我的 WPF 应用程序实现一个未处理的异常处理程序。

App.xaml:

DispatcherUnhandledException="Application_DispatcherUnhandledException"

App.xaml.cs:

 private void Application_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
        {
            MessageBox.Show(e.Exception.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Warning);
            e.Handled = true;
        }

MainWindow.xaml.cs:

    public MainWindow()
    {
        InitializeComponent();

        // Faulty code to trigger unhandled exception
        string s = null;
        s.Trim();
    }

我卡住了,这行不通。错误代码不会显示错误消息,而是将我返回到 Visual Studio 代码编辑器窗口并突出显示错误行。

更新:我已经尝试将错误代码添加到按钮单击事件而不是窗口加载,但同样的问题仍然存在。

btnClickMe_Click(object sender, RoutedEventArgs e)

【问题讨论】:

  • 您是否尝试过在您的MainWindow 构建完成后 触发异常?我怀疑这可能只是一个排序问题 - 窗口是在订阅事件处理程序之前构建的。
  • @JonSkeet 是的,我试过了。但这也没有用。
  • Application.MainWindow is a Window,因此您的MainWindow 在分配给此属性之前必须已实例化。如果这发生在设置DispatcherUnhandledException 之前(而你shouldn't rely on the order that properties are set in XAML),那么当你的异常被抛出时不会安装任何处理程序。
  • 请提供更多关于您尝试的细节(就异常的更“正常”时间而言,例如响应按钮按下)。另外,如果您只是在调试器中点击“继续”会发生什么?是否有可能一切正常,而这只是调试器在事件处理程序之前触发的问题?如果你在调试器中运行代码not会发生什么?
  • 最好将这些信息放在问题中 而不是只放在 cmets 中。那么我的其余评论呢?如果这只是调试器在事件处理程序之前进入的问题,我一点也不感到惊讶……这有时很有用,而在其他时候没有用。

标签: c# wpf


【解决方案1】:

这只是调试器在您的事件处理程序将异常标记为已处理之前进行干预的问题。

只需在调试器中点击“继续”,事件处理程序就会正常触发。 (您也许还可以配置在 VS Code 中如何处理特定异常 - 我知道您可以在 VS 中,但我不知道 VS Code。)

【讨论】: