Wednesday, May 30, 2007

Try and Catch

Please note that there is an error with this entry. See Rule #1 --- Redone for details.


Exceptions are powerful tools that give the developer the ability to understand what is going on with their application, particularly when there is a problem. Sadly, many programmers do not use this feature, or implement it so poorly as to provide no meaningful information.

Rule #1: If you catch an exception, you better record it or re-throw it.

What does this mean? Take a look at the following code:

Catch ex As Exception


End Try


What this code does is catch the exception, then let it get away. It’s like putting cheese on a mouse trap, but then gluing down the trigger so that the mouse can get away. I mean, seriously, what are you thinking? At the least, at the very least, you should have the follow:

Catch ex As Exception


Throw ex


End Try


This at least re-throws the exception so that something above you can make a decision as to what needs to be done. If I had my druthers, however, it would be more like this:

Catch ex As Not Implemented


Throw New Exception("Blow Up3 does not implement that functionality", ex)


Catch es As Exception


Throw New Exception("Unforeseen error in Blow_Up3 trying to access Don’s bank account", ex)


End Try


There is so much more information available to the method that initially gets the exception than the calling method has that it would be a shame to ignore that information and make life more complicated for everyone.

No comments: