Home
C#
TypeInitializationException
This page was last reviewed on 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 tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Sep 11, 2023 (edit).
Home
Changes
© 2007-2024 Sam Allen.