Static Constructors and Exceptions…

…They do not fit together!!!

Many of us like to use static constructors, or type constructors, to initialize static shared fields of a type, but there’s a little problem: if an exception occurrs the runtime will allways wrap it in a TypeInitializationException, which is a bit annoying (although the original exception can be found in the InnerException property). This happens because the static constructor only is executed one time by the runtime, when the type is initialized; the second time the static field is accessed the initial exception will be thrown again and there may not be a way to initialize the field.

The best way to avoid this is to properly catch the exceptions in a type constructor and/or move any potencially dangerous code to static methods or properties, which can be called over and over again.

[Updated - 2005/04/11] – Just a quick footnote: a static constructor is allways executed once: before any instance is created or any of the static members for the class are referenced, so if you move away the creation logic from static constructor define an adequate lock policy, to avoid problems when having multiple calls to your initialization helper methods.

Related Posts (generated)

This website uses IntenseDebate comments, but they are not currently loaded because either your browser doesn't support JavaScript, or they didn't load fast enough.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Switch to our mobile site