C# Type initializer的异常 TypeInitializationException

来源:互联网 发布:js中split 编辑:程序博客网 时间:2024/04/29 17:49

Copy from:http://www.dotnetperls.com/typeinitializationexception

C# TypeInitializationException

Warning: exclamation mark

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 trapped outside of the static constructor reliably.

Example

Framework: NET

First, this example 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.

Essentially, the runtime wraps any exception raised in the static constructor inside a TypeInitializationException. The InnerException of the exception is then the original cause of the problem. The TypeInitializationException is only raised from type initializers.

Program that throws TypeInitializationException [C#]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.    }}OutputUnhandled Exception: System.TypeInitializationException: The type initializer for'Program' threw an exception. --->System.DivideByZeroException: Attempted to divide by zero.   at Program..cctor() in....   --- End of inner exception stack trace ---   at Program.Main()
Main method

The program contains the Program class, which has a static private constructor and a Main entry point. When the Main entry point 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. The runtime then wraps this exception inside a TypeInitializationException.

Fix

Try keyword

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.

Try KeywordCatch Examples

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

Summary

The C# programming language

We demonstrated the TypeInitializationException in the C# language and how it is used to wrap exceptions inside type initializers, also called static constructors. This is a special-purpose exception and 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. The TypeInitializationException then is thrown when the constraints are not met.

原创粉丝点击