Exceptions in static constructors

suggest change

If a static constructor throws an exception, it is never retried. The type is unusable for the lifetime of the AppDomain. Any further usages of the type will raise a TypeInitializationException wrapped around the original exception.

public class Animal
{
    static Animal()
    {
        Console.WriteLine("Static ctor");
        throw new Exception();
    }

    public static void Yawn() {}
}

try
{
    Animal.Yawn();
}
catch (Exception e)
{
    Console.WriteLine(e.ToString());
}

try
{
    Animal.Yawn();
}
catch (Exception e)
{
    Console.WriteLine(e.ToString());
}

This will output:

Static ctor System.TypeInitializationException: The type initializer > for ‘Animal’ threw an exception. —> System.Exception: Exception of > type ‘System.Exception’ was thrown.

[…]

System.TypeInitializationException: The type initializer for ‘Animal’ threw an exception. —> System.Exception: Exception of type ‘System.Exception’ was thrown.

where you can see that the actual constructor is only executed once, and the exception is re-used.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Constructors and Finalizers:
* Exceptions in static constructors

Table Of Contents
17 Regex
19 Arrays
21 Enum
22 Tuples
24 GUID
27 Looping
36 Casting
38 Constructors and Finalizers
46 Methods
88 Events
92 Structs
104 Indexer
106 Stream
107 Timers
109 Threading
127 Caching
135 Pointers
147 C# Script