
You want to review the TypeInitializationException in the C# programming language and .NET Framework, seeing how the exception is thrown from static constructors. The TypeInitializationException actually wraps the errors from static constructors and cannot be trapped outside of the static constructor reliably.
This C# exception article demonstrates TypeInitializationException.

First, this example program shows that the TypeInitializationException in the .NET Framework is raised when an exception is thrown inside a type initializer, also called a static constructor. Essentially, the runtime wraps any exception raised in the static constructor inside a TypeInitializationException. The InnerException of the exception is then the original cause of the problem. The TypeInitializationException is only raised from type initializers.
Program that throws TypeInitializationException [C#]
using System;
class Program
{
static Program()
{
//
// Static constructor for the program class.
// ... Also called a type initializer.
// ... It throws an exception in runtime.
//
int number = 100;
int denominator = int.Parse("0");
int result = number / denominator;
Console.WriteLine(result);
}
static void Main()
{
// Entry point.
}
}
Output
Unhandled Exception: System.TypeInitializationException: The type initializer for
'Program' threw an exception. --->
System.DivideByZeroException: Attempted to divide by zero.
at Program..cctor() in....
--- End of inner exception stack trace ---
at Program.Main()What caused the unhandled exception. The program contains the Program class, which has a static private constructor and a Main entry point. When the Main entry point is reached, the static Program() constructor is executed. The code in the static constructor attempts to divide by zero. This causes a DivideByZeroException to be thrown. The runtime then wraps this exception inside a TypeInitializationException.

Here we note that to fix the TypeInitializationException, you can add try/catch blocks around the body of the static constructor that throws it. If you try to catch the exception inside the Main method, you will not capture it in this program. However, if you wrap the body of the static constructor in a try/catch, you will capture it.

We demonstrated the TypeInitializationException in the C# programming language and how it is used to wrap exceptions inside type initializers, also called static constructors. This is a special-purpose exception and often these errors will be fatal to the program's correct execution. Sometimes, programs will use static constructors to ensure certain constraints are met at startup. The TypeInitializationException then is thrown when the constraints are not met.
Exception Handling