System.TypeInitializationException-klasse

Opmerking

In dit artikel vindt u aanvullende opmerkingen in de referentiedocumentatie voor deze API.

Wanneer een klasse-initialisatiefunctie een type niet kan initialiseren, wordt er een TypeInitializationException gemaakt en wordt een verwijzing doorgegeven naar de uitzondering die is gegenereerd door de klasse-initialisatiefunctie van het type. De InnerException eigenschap van TypeInitializationException houdt de onderliggende uitzondering.

Normaal gesproken weerspiegelt de TypeInitializationException uitzondering een onherstelbare voorwaarde (de runtime kan geen instantie maken van een type) waardoor een toepassing niet kan worden voortgezet. Meestal wordt het TypeInitializationException gegenereerd als reactie op een bepaalde wijziging in de uitvoeringsomgeving van de toepassing. Anders dan mogelijk voor het oplossen van foutopsporingscode, moet de uitzondering daarom niet in een try/catch blok worden verwerkt. In plaats daarvan moet de oorzaak van de uitzondering worden onderzocht en geëlimineerd.

TypeInitializationException maakt gebruik van HRESULT COR_E_TYPEINITIALIZATION, met de waarde 0x80131534.

Voor een lijst van initiële eigenschapswaarden voor een exemplaar van TypeInitializationException, zie de TypeInitializationException-constructoren.

In de volgende secties worden enkele situaties beschreven waarin een TypeInitializationException uitzondering wordt gegenereerd.

Statische constructors

Een statische constructor, indien aanwezig, wordt automatisch aangeroepen door de runtime voordat u een nieuw exemplaar van een type maakt. Statische constructors kunnen expliciet worden gedefinieerd door een ontwikkelaar. Als een statische constructor niet expliciet is gedefinieerd, maken compilers er automatisch een om leden van het type static (in C# of F#) of Shared (in Visual Basic) te initialiseren. Zie Statische constructors voor meer informatie over statische constructors.

Meestal treedt er een TypeInitializationException uitzondering op wanneer een statische constructor een type niet kan instantiëren. De InnerException eigenschap geeft aan waarom de statische constructor het type niet kan instantiëren. Enkele veelvoorkomende oorzaken van een TypeInitializationException uitzondering zijn:

  • Een niet-verwerkte uitzondering in een statische constructor

    Als er een uitzondering wordt gegenereerd in een statische constructor, wordt deze uitzondering verpakt in een TypeInitializationException uitzondering en kan het type niet worden geïnstantieerd.

    Wat deze uitzondering vaak moeilijk op te lossen maakt, is dat statische constructors niet altijd expliciet zijn gedefinieerd in de broncode. Een statische constructor bestaat in een type als:

    • Deze is expliciet gedefinieerd als lid van een type.

    • Het type heeft static variabelen (in C# of F#) of Shared (in Visual Basic) die in één instructie worden gedeclareerd en geïnitialiseerd. In dit geval genereert de taalcompilator een statische constructor voor het type. U kunt het inspecteren met behulp van een hulpprogramma zoals IL Disassembler. Wanneer de C#- en VB-compilers bijvoorbeeld het volgende voorbeeld compileren, genereren ze de IL voor een statische constructor die er ongeveer als volgt uitziet:

    .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
    

    In het volgende voorbeeld ziet u een TypeInitializationException uitzondering die is gegenereerd door een door een compiler gegenereerde statische constructor. De Example klasse bevat een static veld (in C#) of Shared (in Visual Basic) van het type TestClass dat wordt geïnstantieerd door een waarde van 3 door te geven aan de klasseconstructor. Die waarde is echter illegaal; alleen waarden van 0 of 1 zijn toegestaan. Als gevolg hiervan genereert de TestClass klasseconstructor een ArgumentOutOfRangeException. Omdat deze uitzondering niet wordt verwerkt, wordt deze verpakt in een TypeInitializationException uitzondering.

    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(nameof(value));
          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()
    
    Public Class Example1
        Shared test As New TestClass(3)
    
        Public Shared Sub Main()
            Dim ex As New Example1()
            Console.WriteLine(test.Value)
        End Sub
    End Class
    
    Public Class TestClass
       Public ReadOnly Value As Integer
       
       Public Sub New(value As Integer)
            If value < 0 Or value > 1 Then Throw New ArgumentOutOfRangeException(NameOf(value))
            value = value
       End Sub
    End Class
    ' 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()
    

    Houd er rekening mee dat in het uitzonderingsbericht informatie over de InnerException eigenschap wordt weergegeven.

  • Een ontbrekend assembly- of gegevensbestand

    Een veelvoorkomende oorzaak van een TypeInitializationException uitzondering is dat een assembly of gegevensbestand dat aanwezig was in de ontwikkel- en testomgevingen van een toepassing ontbreekt in de runtime-omgeving. U kunt bijvoorbeeld het volgende voorbeeld compileren naar een assembly met de naam Missing1a.dll met behulp van deze opdrachtregelsyntaxis:

    csc -t:library Missing1a.cs
    
    fsc --target:library Missing1a.fs
    
    vbc Missing1a.vb -t:library
    
    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;
       }
    }
    
    open System
    
    type InfoModule(firstUse: DateTime) =
        let mutable ctr = 0
    
        member _.Increment() =
            ctr <- ctr + 1
            ctr
       
        member _.GetInitializationTime() =
            firstUse
    
    Public Class InfoModule
       Private firstUse As DateTime
       Private ctr As Integer = 0
    
       Public Sub New(dat As DateTime)
          firstUse = dat
       End Sub
       
       Public Function Increment() As Integer
          ctr += 1
          Return ctr
       End Function
       
       Public Function GetInitializationTime() As DateTime
          Return firstUse
       End Function
    End Class
    

    Vervolgens kunt u het volgende voorbeeld compileren naar een uitvoerbaar bestand met de naam Missing1.exe door een verwijzing naar Missing1a.dllop te geven:

    csc Missing1.cs /r:Missing1a.dll
    
    vbc Missing1.vb /r:Missing1a.dll
    

    Als u echter de naam van Missing1a.dll wijzigt, verplaatst of verwijdert en het voorbeeld uitvoert, wordt er een TypeInitializationException uitzondering gegenereerd en wordt de uitvoer weergegeven die in het voorbeeld wordt weergegeven. Het uitzonderingsbericht bevat informatie over de InnerException eigenschap. In dit geval is de interne uitzondering een FileNotFoundException uitzondering die wordt gegenereerd omdat de runtime de afhankelijke assembly niet kan vinden.

    using System;
    
    public class MissingEx1
    {
        public static void Main()
        {
            Person p = new Person("John", "Doe");
            Console.WriteLine(p);
        }
    }
    
    public class Person
    {
        static readonly InfoModule s_infoModule;
    
        readonly string _fName;
        readonly string _lName;
    
        static Person()
        {
            s_infoModule = new InfoModule(DateTime.UtcNow);
        }
    
        public Person(string fName, string lName)
        {
            _fName = fName;
            _lName = lName;
            s_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()
    
    open System
    
    type Person(fName, lName) =
        static let infoModule = InfoModule DateTime.UtcNow
        
        do infoModule.Increment() |> ignore
       
        override _.ToString() =
            $"{fName} {lName}"
    let p = Person("John", "Doe")
    
    printfn $"{p}"
    // 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()
    
    Module Example3
        Public Sub Main()
            Dim p As New Person("John", "Doe")
            Console.WriteLine(p)
        End Sub
    End Module
    
    Public Class Person
       Shared infoModule As InfoModule
       
       Dim fName As String
       Dim mName As String
       Dim lName As String
       
       Shared Sub New()
          infoModule = New InfoModule(DateTime.UtcNow)
       End Sub
       
       Public Sub New(fName As String, lName As String)
          Me.fName = fName
          Me.lName = lName
          infoModule.Increment()
       End Sub
       
       Public Overrides Function ToString() As String
          Return String.Format("{0} {1}", fName, lName)
       End Function
    End Class
    ' 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()
    

    Opmerking

    In dit voorbeeld is een TypeInitializationException uitzondering gegenereerd omdat een assembly niet kon worden geladen. De uitzondering kan ook worden gegenereerd als een statische constructor probeert een gegevensbestand te openen, zoals een configuratiebestand, een XML-bestand of een bestand met geserialiseerde gegevens, dat niet kan worden gevonden.

Time-outwaarden voor reguliere expressies vergelijken

U kunt de standaardtime-outwaarde instellen voor een reguliere expressiepatroonkoppelingsbewerking per toepassingsdomein. De time-out wordt gedefinieerd door een TimeSpan waarde voor de eigenschap 'REGEX_DEFAULT_MATCH_TIMEOUT' op te geven voor de AppDomain.SetData methode. Het tijdsinterval moet een geldig TimeSpan object zijn dat groter is dan nul en kleiner is dan ongeveer 24 dagen. Als niet aan deze vereisten wordt voldaan, genereert de poging om de standaardtime-outwaarde in te stellen een ArgumentOutOfRangeException, die op zijn beurt in een TypeInitializationException uitzondering wordt verpakt.

In het volgende voorbeeld ziet u de TypeInitializationException die er wordt gegooid wanneer de toegewezen waarde aan de eigenschap 'REGEX_DEFAULT_MATCH_TIMEOUT' onjuist is. Als u de uitzondering wilt elimineren, stelt u de eigenschap 'REGEX_DEFAULT_MATCH_TIMEOUT' in op een TimeSpan waarde die groter is dan nul en minder dan ongeveer 24 dagen.

using System;
using System.Text.RegularExpressions;

public class RegexEx1
{
    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: {rgx.ToString()}");
        Console.WriteLine($"Timeout interval for this regex: {rgx.MatchTimeout.TotalSeconds} seconds");
    }
}
// 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()
open System
open System.Text.RegularExpressions

let domain = AppDomain.CurrentDomain
// Set a timeout interval of -2 seconds.
domain.SetData("REGEX_DEFAULT_MATCH_TIMEOUT", TimeSpan.FromSeconds -2)

let rgx = Regex "[aeiouy]"
printfn $"Regular expression pattern: {rgx}"
printfn $"Timeout interval for this regex: {rgx.MatchTimeout.TotalSeconds} seconds"
// 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()
Imports System.Text.RegularExpressions

Module Example4
    Public Sub Main()
        Dim domain As AppDomain = AppDomain.CurrentDomain
        ' Set a timeout interval of -2 seconds.
        domain.SetData("REGEX_DEFAULT_MATCH_TIMEOUT", TimeSpan.FromSeconds(-2))

        Dim rgx As New Regex("[aeiouy]")
        Console.WriteLine("Regular expression pattern: {0}", rgx.ToString())
        Console.WriteLine("Timeout interval for this regex: {0} seconds",
                        rgx.MatchTimeout.TotalSeconds)
    End Sub
End Module
' 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()

Agenda's en culturele gegevens

Als u probeert een agenda te instantiëren, maar de runtime het CultureInfo object dat overeenkomt met die agenda niet kan instantiëren, wordt er een TypeInitializationException uitzondering gegenereerd. Deze uitzondering kan worden gegenereerd door de volgende kalenderklasseconstructors:

Aangezien culturele gegevens voor deze culturen beschikbaar moeten zijn op alle systemen, zou u deze uitzondering zelden moeten tegenkomen.