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.

Tagged: , , , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

What’s this?

You are currently reading Bad Programming Examples in C# at JAWS.

meta

Follow

Get every new post delivered to your Inbox.

Join 100 other followers