#817 – What Happens When a Static Constructor Throws an Exception

If any exception is thrown from within a static constructor, a TypeInitializationException will be thrown, with an InnerException set to the original exception that occurred.  At that point, you can no longer access any static data or methods in the class.  You also can’t create any objects of the type using instance constructors.  After the exception, the type is unusable.

    public class Dog
    {
        public static string DogMotto { get; set; }

        static Dog()
        {
            DogMotto = "We serve humans";
            throw new Exception("Oh no");
        }
    }
        static void Main(string[] args)
        {
            try
            {
                Console.WriteLine(Dog.DogMotto);
                Console.WriteLine("After DogMotto output");
            }
            catch (Exception xx)
            {
                Console.WriteLine("Error: {0}", xx.ToString());
            }

817-001

Advertisements