Bug Vanquisher

12 October 2008

Tidbit 2

Filed under: Dev inside!, Tips — Tanveer Badar @ 7:29 PM

This one pertains to CLR.

Please, please, please make sure your static constructors do not throw exceptions. Having static state in a class is already asking for trouble in the case of multiple threads, if that reason wasn’t enough proceed below.

For example,

class A
{
      static DataType1 member1 = new DataType1( );
      static DataType2 member2 = DataType2.GetDefaultInstance( );
}

If there is even the remotest chance that either DataType1’s constructor or DataType2.GetDefaultInstance will throw an exception you are better off with this version:

class A
{

    static DataType1 member1;
    static DataType2 member2

    static A( )
    {
        try
        {
            member1 = new DataType1( );
        }
        catch( Exception ex )
        {
            // do some logging
        }
        try
        {
            member2 = DataType2.GetDefaultInstance( );
        }
        catch( Exception ex )
        {
            // do some logging
        }
    }
}

The only reason for all this hassle is the avoid throwing uncaught exceptions from .cctor of a type.

Because, for a type whose static constructor throws an exception, EE ensures that no instance of that type will ever be instantiated in that appdomain.

[Update 11/03/09: Many moons after the original post, I come across this. The exact same problem happens in native world.]

Advertisements

1 Comment »

  1. […] protecting static initializers with try { … } catch { … } […]

    Pingback by Offenses Of The Highest Order « Bug Vanquisher — 18 October 2008 @ 5:36 PM


RSS feed for comments on this post. TrackBack URI

Leave a Reply

Please log in using one of these methods to post your comment:

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

Create a free website or blog at WordPress.com.

%d bloggers like this: