TypeInitializationException
This occurs when a static
constructor has an error. It is thrown from static
constructors. It wraps the errors from static
constructors.
This exception cannot be reliably trapped outside of the static
constructor. It can be useful when investigating errors in static
constructors.
This program shows that this exception is raised when any exception is thrown inside a type initializer, also called a static
constructor.
static
constructor inside a TypeInitializationException
.InnerException
is the original cause of the problem. The TypeInitializationException
is only raised from type initializers.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. } }Unhandled Exception: System.TypeInitializationException: The type initializer for 'Program' threw an exception. ---> System.DivideByZeroException: Attempted to divide by zero. at Program..cctor.... --- End of inner exception stack trace --- at Program.Main()
When Main
is reached, the static
Program
constructor is executed. The code in the static
constructor attempts to divide by zero.
DivideByZeroException
to be thrown. The runtime then wraps this exception inside a TypeInitializationException
.To fix this error, you can add try-catch
blocks around the body of the static
constructor that throws it. Alternatively, you could avoid the exception with an if
-statement.
TypeInitializationException
is used to wrap exceptions inside type initializers, also called static
constructors. This is a special-purpose exception.