如何在 WPF 应用程序中拦截 NotImplementedException?
如何在 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 被埋在远离接口的地方,则不起作用。
如何捕获所有此类异常并显示消息框?
How do I intercept a NotImplementedException in a WPF application?
I'll occasionally throw a NotImplementedException while testing my in-progress WPF application:
Private Sub ButtonDoSomething_Click(...) Handles ButtonDoSomething.Click
Throw New NotImplementedException( _
"ButtonDoSomething_Click() not implemented.")
End Sub
But, I'd rather these not crash the program.
I could replace all such exception throws with:
MessageBox.Show("ButtonDoSomething_Click() not implemented.", _
"Not Implemented", MessageBoxButton.OK, MessageBoxImage.Information)
But that seems inellegant somehow and wouldn't work if the NotImplementedException was buried away from the interface.
How can I capture all such exceptions and display a message box?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以附加到 Application 类上的 DispatcherUnhandledException 事件,每当发生未处理的异常时都会引发该事件。 在那里,您可以检查传递给事件处理程序的 DispatcherUnhandledExceptionEventArgs 实例的 Exception 属性,以查看它是否属于 NotImplementedException 类型。 如果是,则将 Handled 属性设置为 true,然后返回。
应该注意的是,如果您调用 MsgBox 而不是抛出异常,则会遇到必须实际返回某些内容并设置所有 out/ref 参数的问题,这将是额外的开销。
You can attach to the DispatcherUnhandledException event on the Application class, which will be raised anytime an unhandled exception occurs. In there, you can check the Exception property on the DispatcherUnhandledExceptionEventArgs instance passed to the event handler to see if it is of type NotImplementedException. If it is, then set the Handled property to true, and then return.
It should be noted that if you called MsgBox instead of throwing the exception, you would have the problem of having to actually return something and set all out/ref parameters as well, which would have been additional overhead.
查看 Application.DispatcherUnhandledException 或 AppDomain.UnhandledException。 两者都可以让您处理未处理的异常。
Have a look at Application.DispatcherUnhandledException or AppDomain.UnhandledException. Both let you handle otherwise unhandled exceptions.
您可以使用 调试.失败。 例如:
它将弹出一个消息框,其中包含您提供的文本,并向您显示堆栈跟踪。
Instead of throwing a NotImplementedException or using a MessageBox, you can use Debug.Fail. For example:
It will pop up a message box with the text you provide and show you the stack trace.