views:

395

answers:

3

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?

+6  A: 

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.

casperOne
+3  A: 

Have a look at Application.DispatcherUnhandledException or AppDomain.UnhandledException. Both let you handle otherwise unhandled exceptions.

Jakob Christensen
True, however, AppDomain.UnhandledException is an event which is raised by the AppDomain when an unhandled exception is detected. No matter what you do, the app will shutdown right after.
siz
A: 

Instead of throwing a NotImplementedException or using a MessageBox, you can use Debug.Fail. For example:

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

It will pop up a message box with the text you provide and show you the stack trace.

John Myczek