Exception handling in programming is an essential piece, necessary to keep our applications from puking all over the place (we've all had it happen at least once in our career and it's not fun to read that email or field that call). Fortunately C# (.Net Framework) offers us a nice mechanism for exception handling, structured exception handling.
Exceptions are reporting mechanisms for providing information about the error that occurred, and when dealing with error checking & exception handling the more you can gather the better off you are (whether it be an unexpected, unhandled exception, or a caught/thrown exception). The Exception class offers the following properties (these are the most utilized anyways, there are more that can be found here)
- Message: Holds the actual message from the exception.
- Source: What application/object did the exception occur in.
- TargetSite: The method that threw the exception.
- StackTrace: The actual call stack of the exception
Ok enough describing what C# has to offer for exception handling, let's take a look at some points that should always be remembered when exception handling:
- Use a single try with multiple catch blocks: It's always better to have one try statement with many/multiple catch statmeents for handling different exception typed.
- Order catch blocks in proper order If you use multiple catch blocks always place them in the proper order: From most specific to most general exceptions. This makes it clearer when coming back to your code or when someone else is reading your code.
- Always come back to a valid state: Always make sure you get into a valid state, make sure the application can move forward and no severe side effects have occurred from the exception before moving forward.
- When throwing, throw closest matching exception: Make sure, when throwing an exception, that you pick the exception that closet resembles what has taken place, especially in situations where more than one exception can describe what has just happened.
- Extend Application not System.Extension: When creating your own custom exceptions always extend the ApplicationExtension class, this will help keep your exceptions in a different hierarchy.
- When rethrowing always use InnerException: This will help keep the inner cause of the initial exception in tact, especially with linked/nested exceptions.
Now that I have my spiel out of the way, what best practices do you require yourself and other developers to stick by when it comes to exception handling in your C# applications. While my list is by no means exhaustive I feel those are at the top of my list to adhere to when handling exceptions