Source Code: Download
This is the first post on my goal of writing 3 substantial posts by the end of the year. I decided to write this post on exception handling more specifically writing a Custom Exception. Why would we want to have custom exceptions.
The first reason to create an exception is because the exception you want does not exist. If there is not an exception in the system the has the functionality you are looking for then you need to create one. This gives you the ability add custom data to your exceptions. Now you can pass this data, in the exception, to your logging/handling mechanism.
The second reason would wrap system exception to provide more data. Like above you can add data to your exception and include the system exception as an inner exception.
One thing to keep in mind while working with exceptions is the overhead involved with exception handling. You should only throw and or catch exceptions when you are able to recover from them gracefully and or want to log them. This brings us to another point about exception handling, catch and work with the most specific exception you can. For instance catching a FileNotFoundException instead of a ApplicationException may make more sense. This is where you custom exceptions can come in handy.
How Do We Create One
When creating custom exceptions I like to put them in their own project. That way I can add a reference to all my other projects (UI, DAL, BLL) and have a common exception framework throughout.
Step1: Create a class that inherits from Exception. This class should be Serializable :
Step 2: Create some variables to hold your custom data.
Step 3: Create constructors to handle the different scenarios:
Step 4: Override the ToString method to display custom data and inner exception data:
Now you have a basic custom exception. You can add as much functionality as needed such as adding a HelpLink. Since you are inheriting from Exceptions the possibilities are endless.
How Do We Use Our Exception
Using your exception is just as easy as adding a reference to your project and off you go. I have created a DTO project with a person object. In my exception I want to capture the person object and the IP address of the machine.
Here is an example of using my custom exception. This example shows catching a general exception (not good practice) and log the exception to the event viewer. It also writes the exception out to the screen:
Here is what the exception looks like in the Event Viewer. Notice the custom data (IP Address and Person):
Here is what the code would look like when wrapping a system exception:
and now in the Event Viewer (notice the inner exception):
You now have the tools you need to create and use custom exceptions while maintaining the rich functionality in the native Exception Framework.
You can get the source code to my demo code here.