Exception Handling Worst Practices

Oh, my eyes! I'm currently looking at a VB.NET class which includes a dozen examples of the following exception "handling" anti-pattern:

'Send e-mail  
Dim smtp As New SmtpClient()  
Catch ex As Exception  
End Try  

Why would anyone write code like this?!

This violates some of the most fundamental of best practices to be followed when writing exception handling code, including:

  • Not catching System.Exception (which should really only be caught in one place per thread, at the top of your stack).
  • Not throwing System.Exception (instead of an appropriate custom exception class).
  • Not catching exceptions that you can't handle (if the best you can do is rethrow the exception like a hot potato, then why bother? Just let it bubble up).
  • Clearing the stack trace when rethrowing (in the example above, a new exception is thrown, with a cleared stack trace. Valuable debugging information has been lost).

I can only assume that the original author of this code didn't understand the concept of exception handling whatsoever.

Still, this is all easily solved by me and my trusty Delete key :-)