Bad Programming Examples in C#

23 February, 2009 § Leave a comment

I’m starting to compile a list of constructs I’ve seen in production C# code that needs to be modified. Code Analysis will flag most of these. Here is the first of them, with more to be added later:

1. Never leave a blank catch statement or use catch(Exception)

In C#, if you write catch(Exception) or a blank catch, the exception will be casted to a System.Object. This will also catch non-CLS compliant exceptions. If you can’t do anything to remedy the exceptional situation, you shouldn’t be catching the exception. Usually when you see a code construct like this, the exception is rethrown. Not only is this unnecessary and bad programming, it ruins the stack trace and any other important information that Windows Error Reporting can provide for you.

If you are unsure what type of exception can be thrown, you should check the documentation. If you are catching the exception so that you can perform some cleanup before exiting, then you should move that cleanup code to a finally block. If the latter is the case, then you probably don’t need the catch block there in the first place.

If you run Code Analysis on your code, you will receive a CatchNonClsCompliantExceptionsInGeneralHandlers warning.

More information can be found about why not to have empty catches in your code at the CLR Team Blog.

Where Am I?

You are currently browsing entries tagged with exceptions at JAWS.

Follow

Get every new post delivered to your Inbox.

Join 998 other followers