C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Info: The runtime wraps any exception raised in the static constructor inside a TypeInitializationException.
And: 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()
And: The runtime then wraps this exception inside a TypeInitializationException.
However: If you wrap the body of the static constructor in a try-catch block, you will capture it.
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.