Home
C#
TypeInitializationException
Updated Sep 11, 2023
Dot Net Perls
TypeInitializationException. This occurs when a static constructor has an error. It is thrown from static constructors. It wraps the errors from static constructors.
A warning. This exception cannot be reliably trapped outside of the static constructor. It can be useful when investigating errors in static constructors.
static
Exception
This program shows that this exception is raised when any exception is thrown inside a type initializer, also called a static constructor.
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.
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()
Notes, program. When Main is reached, the static Program constructor is executed. The code in the static constructor attempts to divide by zero.
And This causes a DivideByZeroException to be thrown. 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. Alternatively, you could avoid the exception with an if-statement.
try
catch
if
A summary. TypeInitializationException is used to wrap exceptions inside type initializers, also called static constructors. This is a special-purpose exception.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Sep 11, 2023 (edit).
Home
Changes
© 2007-2025 Sam Allen