I’m often asked to assist with some basic exception handling strategies for code. Below are a few exception handling pointers and hopefully expand on them in later posts.
· After identifying suspect code, determine if it will benefit from exception handling, the tester-doer pattern or the try.parse pattern. There are some times you won’t want to use a try/catch, (e.g. check to see if a connection is closed first before closing it rather than wrapping the close call in a try catch).
· Where possible, catch specific exceptions, not just System.Exception. (i.e. If you know the exception to be caught will be a SqlException, catch that)
· Don’t use return error/success codes and rely on other developers (or yourself) to use or check the value of return codes. More often than not, return values/codes from a function are just wasted.
· Exceptions aren’t always errors. Exceptions can represent errors but they can represent anything that isn’t ordinarily going to happen during the execution of your code, and that isn't always an error.
· Use the finally block. You’ll be able to save half the coding and coding around other code you’d normally need to do without it. If you don’t use a finally block, not only will you have to check for specific states of variables yourself to cleanup code when an exception has occurred, but you will have to check these flags/variables again when things run smooth. Finally trims code and makes things smoother.
· Make sure the state of the application hasn’t changed after the exception. There is one of two states that you want to leave an application method after an exception, 1) the state the app was in before the method call or 2) as if the method had never run before. Either way, if an exception occurs, you have some work to do to make sure the app state is solid.
· Users should never have to see or deal with an exception that has been bubbled all the way up the stack. Not only does break the state rule but the user has just lost confidence in this application. The only worse thing you can do to the user now is to have the app hang all day.
· Log all exceptions. By logging all exceptions, you can generate information, metrics and reports about the internal state of the program to perform diagnostics and create a better quality version next release.



