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.

Finally will execute, even after return

7 January, 2009 § Leave a comment

How’s this for weird looking code?

public static void RunSnippet()
{
    var y = testFinally();
    if( y == 99 )
    {
        WL("It is 99");
    }
    else
    {
        WL("It is 6");
    }
}

public static int? testFinally()
{
    int? x = 99;
    try
    {
        return x;
    }
    finally
    {
        x = 6;   
    }
    return x;
}

What happens? testFinally will return 99. If you changed the finally block to set x equal to null, the same result will happen. When there is a finally block, the function will not return until after the finally block has finished, regardless of any code following it. The second return statement is never reached. Also, you cannot return from a finally block, since control flow statements cannot be made in a finally block.

The code above was written with SnippetCompiler, a really nice free tool to have at your side when you want to test something out but don’t want to create a new solution in Visual Studio.

The Behavior of a Using Statement

14 November, 2008 § Leave a comment

C# comes right out of the box with it’s own garbage collector. When objects are no longer referenced and go out of scope, they are then marked for garbage collection. Some of these objects may have special properties.

They may carry handles to files, connections to databases, etc. When the garbage collector picks these objects up, it doesn’t really know what to do with these associations.

Cleverly, there is an interface to solve this. It’s called IDisposable. With IDisposable, you are required to implement one function, Dispose(). Dispose can be compared to the C++ destructor. File buffers and database connections can all be closed right within Dispose.

This seems nice, but awkward to call Dispose on an object when you are done with it. It would be nice to just nest that object in a block statement so it is easier to see from a glance when a specific object is not needed. It would also be nice if that Dispose method could be called when the block is finished.

This brings us towards a using statement. Here is an example:

ResultSet resultSet;
using( var sqlConnection = new SqlConnection() )
{
  resultSet = sqlConnection.ExecuteQuery( "select * from `products`" );
  sqlConnection.ExecuteNonQuery( "delete from `products`" );
}
...
...  //messing around with the result set
...
return resultSet;

« Read the rest of this entry »

C++ Function Try Blocks

14 November, 2008 § 1 Comment

Will it compile?

That is the question for this post. Suppose you have a class definition and constructor with an object initializer list like the following:

class CObject
{
   CFoo foo;
   CBar bar;
};

CObject::CObject() : foo(2), bar(3) {}

« Read the rest of this entry »

Where Am I?

You are currently browsing entries tagged with try catch at JAWS.