Dieser Artikel wurde maschinell übersetzt. Wenn Sie die englische Version des Artikels anzeigen möchten, aktivieren Sie das Kontrollkästchen Englisch. Sie können den englischen Text auch in einem Popupfenster anzeigen, indem Sie den Mauszeiger über den Text bewegen.
Übersetzung
Englisch

TypeInitializationException-Klasse

 

Die Ausnahme, die als Wrapper um die von dieser Klasseninitialisierung ausgelöste Ausnahme ausgelöst wird. Diese Klasse kann nicht vererbt werden.

Namespace:   System
Assembly:  mscorlib (in mscorlib.dll)

System.Object
  System.Exception
    System.SystemException
      System.TypeInitializationException

[SerializableAttribute]
[ComVisibleAttribute(true)]
public sealed class TypeInitializationException : SystemException

NameBeschreibung
System_CAPS_pubmethodTypeInitializationException(String, Exception)

Initialisiert eine neue Instanz der TypeInitializationException -Klasse mit der Fehlermeldung, dem angegebenen Typnamen und einen Verweis auf die innere Ausnahme, die die Ursache dieser Ausnahme ist.

NameBeschreibung
System_CAPS_pubpropertyData

Ruft eine Auflistung von Schlüssel-Wert-Paaren ab, die zusätzliche benutzerdefinierte Informationen über die Ausnahme bereitstellen.(Geerbt von „Exception“.)

System_CAPS_pubpropertyHelpLink

Ruft einen Link zur Hilfedatei ab, die dieser Ausnahme zugeordnet ist, oder legt einen Link fest.(Geerbt von „Exception“.)

System_CAPS_pubpropertyHResult

Ruft HRESULT ab oder legt HRESULT fest. Dies ist ein codierter Wert, der einer bestimmten Ausnahme zugeordnet ist.(Geerbt von „Exception“.)

System_CAPS_pubpropertyInnerException

Ruft die Exception-Instanz ab, die die aktuelle Ausnahme verursacht hat.(Geerbt von „Exception“.)

System_CAPS_pubpropertyMessage

Ruft eine Meldung ab, die die aktuelle Ausnahme beschreibt.(Geerbt von „Exception“.)

System_CAPS_pubpropertySource

Gibt den Namen der Anwendung oder des Objekts zurück, die bzw. das den Fehler verursacht hat, oder legt diesen fest.(Geerbt von „Exception“.)

System_CAPS_pubpropertyStackTrace

Ruft eine Zeichenfolgendarstellung der unmittelbaren Frames in der Aufrufliste ab.(Geerbt von „Exception“.)

System_CAPS_pubpropertyTargetSite

Ruft die Methode ab, die die aktuelle Ausnahme auslöst.(Geerbt von „Exception“.)

System_CAPS_pubpropertyTypeName

Ruft den vollqualifizierten Namen des Typs, der nicht initialisiert werden kann.

NameBeschreibung
System_CAPS_pubmethodEquals(Object)

Bestimmt, ob das angegebene Objekt mit dem aktuellen Objekt identisch ist.(Geerbt von „Object“.)

System_CAPS_pubmethodGetBaseException()

Gibt beim Überschreiben in einer abgeleiteten Klasse eine Exception zurück, die die ursprüngliche Ursache für eine oder mehrere nachfolgende Ausnahmen ist.(Geerbt von „Exception“.)

System_CAPS_pubmethodGetHashCode()

Fungiert als die Standardhashfunktion.(Geerbt von „Object“.)

System_CAPS_pubmethodGetObjectData(SerializationInfo, StreamingContext)

Legt die SerializationInfo -Objekt mit dem Typnamen und zusätzlichen Informationen zur Ausnahme.(Überschreibt Exception.GetObjectData(SerializationInfo, StreamingContext).)

System_CAPS_pubmethodGetType()

Ruft den Laufzeittyp der aktuellen Instanz ab.(Geerbt von „Exception“.)

System_CAPS_pubmethodToString()

Erstellt eine Zeichenfolgendarstellung der aktuellen Ausnahme und gibt diese zurück.(Geerbt von „Exception“.)

When a class initializer fails to initialize a type, a T:System.TypeInitializationException is created and passed a reference to the exception thrown by the type's class initializer. The P:System.Exception.InnerException property of T:System.TypeInitializationException holds the underlying exception.

Typically, the T:System.TypeInitializationException exception reflects a catastrophic condition (the runtime is unable to instantiate a type) that prevents an application from continuing. Most commonly, the T:System.TypeInitializationException is thrown in response to some change in the executing environment of the application. Consequently, other than possibly for troubleshooting debug code, the exception should not be handled in a try/catch block. Instead, the cause of the exception should be investigated and eliminated.

TypeInitializationException uses the HRESULT COR_E_TYPEINITIALIZATION, which has the value 0x80131534.

For a list of initial property values for an instance of T:System.TypeInitializationException, see the M:System.TypeInitializationException.#ctor(System.String,System.Exception) constructors.

The following sections describe some of the situations in which a T:System.TypeInitializationException exception is thrown.

Static constructors and the TypeInitializationException exception
Regular expression match timeout values
Calendars and cultural data

A static constructor, if one exists, is called automatically by the runtime before creating a new instance of a type. Static constructors can be explicitly defined by a developer. If a static constructor is not explicitly defined, compilers automatically create one to initialize any static (in C#) or Shared (in Visual Basic) members of the type. For more information on static constructors, see Static Constructors (C# Programming Guide).

Most commonly, a T:System.TypeInitializationException exception is thrown when a static constructor is unable to instantiate a type. The P:System.Exception.InnerException property indicates why the static constructor was unable to instantiate the type. Some of the more common causes of a T:System.TypeInitializationException exception are:

An unhandled exception in a static constructor

If an exception is thrown in a static constructor, that exception is wrapped in a T:System.TypeInitializationException exception, and the type cannot be instantiated.

What often makes this exception difficult to troubleshoot is that static constructors are not always explicitly defined in source code. A static constructor exists in a type if:

  • It has been explicitly defined as a member of a type.

  • The type has static (in C#) or Shared (in Visual Basic) variables that are declared and initialized in a single statement. In this case, the language compiler generates a static constructor for the type. You can inspect it by using a utility such as IL Disassembler. For instance, when the C# and VB compilers compile the following example, they generate the IL for a static constructor that is similar to this:

    
    .method private specialname rtspecialname static 
            void  .cctor() cil managed
    {
      // Code size       12 (0xc)
      .maxstack  8
      IL_0000:  ldc.i4.3
      IL_0001:  newobj     instance void TestClass::.ctor(int32)
      IL_0006:  stsfld     class TestClass Example::test
      IL_000b:  ret
    } // end of method Example::.cctor
    
    

The following example shows a T:System.TypeInitializationException exception thrown by a compiler-generated static constructor. The Example class includes a static (in C#) or Shared (in Visual Basic) field of type TestClass that is instantiated by passing a value of 3 to its class constructor. That value, however, is illegal; only values of 0 or 1 are permitted. As a result, the TestClass class constructor throws an T:System.ArgumentOutOfRangeException. Since this exception is not handled, it is wrapped in a T:System.TypeInitializationException exception.

using System;

public class Example
{
   private static TestClass test = new TestClass(3);

   public static void Main()
   {
      Example ex = new Example();
      Console.WriteLine(test.Value);
   }
}

public class TestClass
{
   public readonly int Value;

   public TestClass(int value)
   {
      if (value < 0 || value > 1) throw new ArgumentOutOfRangeException();
      Value = value;
   }
}
// The example displays the following output:
//    Unhandled Exception: System.TypeInitializationException: 
//       The type initializer for 'Example' threw an exception. ---> 
//       System.ArgumentOutOfRangeException: Specified argument was out of the range of valid values.
//       at TestClass..ctor(Int32 value)
//       at Example..cctor()
//       --- End of inner exception stack trace ---
//       at Example.Main()

Note that the exception message displays information about the P:System.Exception.InnerException property.

A missing assembly or data file

A common cause of a T:System.TypeInitializationException exception is that an assembly or data file that was present in an application's development and test environments is missing from its runtime environment. For example, you can compile the following example to an assembly named Missing1a.dll by using the this command-line syntax:

csc /t:library Missing1a.cs
using System;

public class InfoModule
{
   private DateTime firstUse;
   private int ctr = 0;

   public InfoModule(DateTime dat)
   {
      firstUse = dat;
   }

   public int Increment()
   {
      return ++ctr;
   }

   public DateTime GetInitializationTime()
   {
      return firstUse;
   }
}

You can then compile the following example to an executable named Missing1.exe by including a reference to Missing1a.dll:

csc Missing1.cs /r:Missing1a.dll

However, if you rename, move, or delete Missing1a.dll and run the example, it throws a T:System.TypeInitializationException exception and displays the output shown in the example. Note that the exception message includes information about the P:System.Exception.InnerException property. In this case, the inner exception is a T:System.IO.FileNotFoundException that is thrown because the runtime cannot find the dependent assembly.

using System;

public class Example
{
   public static void Main()
   {
      Person p = new Person("John", "Doe");
      Console.WriteLine(p);   
   }
}

public class Person
{
   static InfoModule infoModule;

   String fName;
   String mName;
   String lName;

   static Person()
   {
      infoModule = new InfoModule(DateTime.UtcNow);
   }

   public Person(String fName, String lName)
   {
      this.fName = fName;
      this.lName = lName;
      infoModule.Increment();
   }

   public override String ToString()
   {
      return String.Format("{0} {1}", fName, lName);
   }
}
// The example displays the following output if missing1a.dll is renamed or removed:
//    Unhandled Exception: System.TypeInitializationException: 
//       The type initializer for 'Person' threw an exception. ---> 
//       System.IO.FileNotFoundException: Could not load file or assembly 
//       'Missing1a, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' 
//       or one of its dependencies. The system cannot find the file specified.
//       at Person..cctor()
//       --- End of inner exception stack trace ---
//       at Person..ctor(String fName, String lName)
//       at Example.Main()
System_CAPS_noteHinweis

In this example, a T:System.TypeInitializationException exception was thrown because an assembly could not be loaded. The exception can also be thrown if a static constructor attempts to open a data file, such as a configuration file, an XML file, or a file containing serialized data, that it cannot find.

You can set the default timeout value for a regular expression pattern matching operation on a per-application domain basis. The timeout is defined by a specifying a T:System.TimeSpan value for the "REGEX_DEFAULT_MATCH_TIMEOUT" property to the M:System.AppDomain.SetData(System.String,System.Object) method. The time interval must be a valid T:System.TimeSpan object that is greater than zero and less than approximately 24 days. If these requirements are not met, the attempt to set the default timeout value throws an T:System.ArgumentOutOfRangeException, which in turn is wrapped in a T:System.TypeInitializationException exception.

The following example shows the T:System.TypeInitializationException that is thrown when the value assigned to the "REGEX_DEFAULT_MATCH_TIMEOUT" property is invalid. To eliminate the exception, set the"REGEX_DEFAULT_MATCH_TIMEOUT" property to a T:System.TimeSpan value that is greater than zero and less than approximately 24 days.

using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      AppDomain domain = AppDomain.CurrentDomain;
      // Set a timeout interval of -2 seconds.
      domain.SetData("REGEX_DEFAULT_MATCH_TIMEOUT", TimeSpan.FromSeconds(-2));

      Regex rgx = new Regex("[aeiouy]");
      Console.WriteLine("Regular expression pattern: {0}", rgx.ToString());
      Console.WriteLine("Timeout interval for this regex: {0} seconds",
                        rgx.MatchTimeout.TotalSeconds);
   }
}
// The example displays the following output:
//    Unhandled Exception: System.TypeInitializationException: 
//       The type initializer for 'System.Text.RegularExpressions.Regex' threw an exception. ---> 
//       System.ArgumentOutOfRangeException: Specified argument was out of the range of valid values.
//       Parameter name: AppDomain data 'REGEX_DEFAULT_MATCH_TIMEOUT' contains an invalid value or 
//       object for specifying a default matching timeout for System.Text.RegularExpressions.Regex.
//       at System.Text.RegularExpressions.Regex.InitDefaultMatchTimeout()
//       at System.Text.RegularExpressions.Regex..cctor()
//       --- End of inner exception stack trace ---
//       at System.Text.RegularExpressions.Regex..ctor(String pattern)
//       at Example.Main()

If you attempt to instantiate a calendar but the runtime is unable to instantiate the T:System.Globalization.CultureInfo object that corresponds to that calendar, it throws a T:System.TypeInitializationException exception. This exception can be thrown by the following calendar class constructors:

  • The default constructor of the T:System.Globalization.JapaneseCalendar class.

  • The default constructor of the T:System.Globalization.KoreanCalendar class.

  • The default constructor of the T:System.Globalization.TaiwanCalendar class.

Since cultural data for these cultures should be available on all systems, you should rarely, if ever, encounter this exception.

Universelle Windows-Plattform
Verfügbar seit 8
.NET Framework
Verfügbar seit 1.1
Portierbare Klassenbibliothek
Unterstützt in: portierbare .NET-Plattformen
Silverlight
Verfügbar seit 2.0
Windows Phone Silverlight
Verfügbar seit 7.0
Windows Phone
Verfügbar seit 8.1

Alle öffentlichen statischen Member ( Shared in Visual Basic) dieses Typs sind threadsicher. Die Threadsicherheit für Instanzmember ist nicht garantiert.

Zurück zum Anfang
Anzeigen: