0

如何在 WPF 应用程序中拦截 NotImplementedException?

在测试正在进行的 WPF 应用程序时,我偶尔会抛出 NotImplementedException:

Private Sub ButtonDoSomething_Click(...) Handles ButtonDoSomething.Click
    Throw New NotImplementedException( _
        "ButtonDoSomething_Click() not implemented.")
End Sub

但是,我宁愿这些不会使程序崩溃。

我可以将所有此类异常抛出替换为:

MessageBox.Show("ButtonDoSomething_Click() not implemented.", _
    "Not Implemented", MessageBoxButton.OK, MessageBoxImage.Information)

但这似乎有点不雅,如果 NotImplementedException 被埋没在接口之外,这将不起作用。

如何捕获所有此类异常并显示消息框?

4

3 回答 3

6

您可以附加到 Application 类上的 DispatcherUnhandledException 事件,该事件将在发生未处理的异常时引发。在那里,您可以检查传递给事件处理程序的 DispatcherUnhandledExceptionEventArgs 实例的 Exception 属性,以查看它是否属于 NotImplementedException 类型。如果是,则将 Handled 属性设置为 true,然后返回。

应该注意的是,如果您调用 MsgBox 而不是抛出异常,您将遇到必须实际返回某些内容并设置所有 out/ref 参数的问题,这将是额外的开销。

于 2009-02-12T16:07:10.887 回答
3

查看 Application.DispatcherUnhandledException 或 AppDomain.UnhandledException。两者都可以让您处理其他未处理的异常。

于 2009-02-12T16:08:37.420 回答
0

您可以使用Debug.Fail,而不是抛出 NotImplementedException 或使用 MessageBox 。例如:

Debug.Fail("This method is not implemented yet!");

它将弹出一个带有您提供的文本的消息框,并向您显示堆栈跟踪。

于 2009-02-12T22:22:42.293 回答