C#: Try to catch and log that exception!

-Uses the app in the previous post, “XAML/C#: Creating a button and an event”-

I noticed that on my recent WPF application that when I clicked my save button without entering any information in my little form that it would crash with a NullRef Exception on the combo box.


Figured it would be a good time to revisit the Try Catch statement and handle myself an exception.

I removed the MessageBox portion of the SaveButton event because I wasn’t too fond of it and encased the StringBuilder in a Try block. Since I know the exception that I’m getting is a NullRef, a NullReferenceException is placed in the Catch statement.


My application will no longer fail should an item not be chosen from the ComboBox, but I have two problems now.
Num1: Since I chopped the MessageBox my save button doesn’t really do anything again except build a string anyways.
Num2: If the save button did do something, and instead of the application crashing we keep it up to make it more user friendly, what information do we have now on why it wasn’t performing its task?

Solutions – Create a log that’ll save the information when the controls are filled out correctly and keep a separate log that’ll report the errors when they occur. This way our button will have a purpose and we’ll have information as to why the button may have not worked for whatever reason.


Then to just put the Logger in action.


And then to test out the application…


I’d say it was a success 😛


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s