C#:.NET:Exception

.NET Array Dictionary List String 2D Async DataTable Dates DateTime Enum File For Foreach Format IEnumerable If IndexOf Lambda Parse Path Process Property Regex Replace Row Sort Split Static StringBuilder Substring Switch Tuple Window

TypeInitializationException occurs when a static constructor has an error. It is thrown from static constructors. It actually wraps the errors from static constructors. It cannot be reliably trapped outside of the static constructor.Static Constructor
Example. We test this exception in an example program. This program shows that this exception in the .NET Framework is raised when any exception is thrown inside a type initializer, also called a static constructor.
The runtime wraps any exception raised in the static constructor inside a TypeInitializationException. The InnerException is the original cause of the problem. The TypeInitializationException is only raised from type initializers.
C# program that throws TypeInitializationException

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....
   --- End of inner exception stack trace ---
   at Program.Main()
When the Main method 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.

And: The runtime then wraps this exception inside a TypeInitializationException.


Fix. To fix this error, 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.TryCatch

However: If you wrap the body of the static constructor in a try-catch block, you will capture it.


Summary. TypeInitializationException is used to wrap exceptions inside type initializers, also called static constructors. This is a special-purpose exception. 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.

And: The TypeInitializationException then is thrown when the constraints are not met.