System.TypeInitializationException クラス

この記事では、この API のリファレンス ドキュメントへの補足的な解説を提供します。

クラス初期化子で型の初期化に失敗すると、TypeInitializationException が作成され、その型のクラス初期化子でスローされる例外への参照が渡されます。 TypeInitializationExceptionInnerException プロパティは、内部的な例外を保持します。

通常、TypeInitializationException 例外は、アプリケーションの継続を妨げる致命的な (ランタイムが型のインスタンスを作成できない) 状態を反映します。 最も一般的には、TypeInitializationException は、アプリケーションの実行環境における何らかの変化に応じてスローされます。 したがって、デバッグ コードのトラブルシューティングを行う場合を除き、この例外は try/catch ブロック内でハンドルするべきではありません。 代わりに、この例外の原因を調査して排除する必要があります。

TypeInitializationException は HRESULT COR_E_TYPEINITIALIZATION を使用し、これは値 0x80131534 を持ちます。

インスタンスの初期プロパティ値の一覧についてはTypeInitializationExceptionを参照してください、TypeInitializationExceptionコンス トラクター。

以下のセクションでは、TypeInitializationException 例外がスローされる状況の一部について説明します。

静的コンストラクター

静的コンストラクターが存在する場合、型の新しいインスタンスを作成する前に、静的コンストラクターがランタイムによって自動的に呼び出されます。 静的コンストラクターは、開発者が明示的に定義できます。 静的コンストラクターが明示的に定義されていない場合、コンパイラは、その型の static メンバー (C# または F#) または Shared メンバー (Visual Basic) を初期化するために自動的に静的コンストラクターを作成します。 静的コンストラクターの詳細については、「静的コンストラクター」を参照してください。

最も一般的には、TypeInitializationException 例外は、静的コンストラクターが型のインスタンスを作成できない場合にスローされます。 InnerException プロパティは、静的コンストラクターがその型のインスタンスを作成できなかった理由を示します。 TypeInitializationException 例外のその他の一般的な原因の一部を以下に示します。

  • 静的コンストラクター内のハンドルされない例外

    静的コンストラクター内で例外がスローされた場合、その例外は TypeInitializationException 例外にラップされ、その型のインスタンスを作成することはできません。

    この例外のトラブルシューティングをしばしば困難にする原因は、静的コンストラクターが必ずしもソース コード内で明示的に定義されているとは限らないという事実です。 型の中に静的コンストラクターが存在するのは以下の場合です。

    • 型のメンバーとして明示的に定義されている場合。

    • 型が、1 つのステートメントで宣言および初期化される static 変数 (C# または F#) または Shared 変数 (Visual Basic) を持つ場合。 この場合、言語コンパイラは型の静的コンストラクターを生成します。 これは、IL Disassembler などのユーティリティを使用することで調べることができます。 たとえば、C# と VB コンパイラは、以下の例をコンパイルする際に、次のような静的コンストラクターの IL を生成します。

    .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
    

    次の例は、コンパイラによって生成された静的コンストラクターによってスローされる TypeInitializationException 例外を示しています。 Example クラスには、3 という値をクラス コンストラクターに渡すことによってインスタンスが作成される型 TestClassstatic フィールド (C#) または Shared フィールド (Visual Basic) が含まれます。 しかし、この値は無効です。許可される値は 0 または 1 のみです。 結果として、TestClass クラス コンストラクターは ArgumentOutOfRangeException をスローします。 この例外はハンドルされないため、TypeInitializationException 例外でラップされます。

    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()
    

    例外メッセージには、InnerException プロパティに関する情報が表示されることに注意してください。

  • アセンブリまたはデータ ファイルが見つからない

    TypeInitializationException 例外の一般的な原因は、アプリケーションの開発環境およびテスト環境には存在していたアセンブリまたはデータ ファイルがランタイム環境には存在しないことです。 たとえば、次のコマンド ライン構文を使用することで、以下の例を Missing1a.dll という名前のアセンブリにコンパイルできます。

    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
    

    その後、Missing1a.dll への参照を含めて、以下の例を Missing1.exe という名前の実行可能ファイルにコンパイルできます。

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

    しかし、Missing1a.dll の名前変更、移動、または削除を行い、例を実行すると、TypeInitializationException 例外がスローされ、例に示されている出力が表示されます。 例外メッセージには、InnerException プロパティに関する情報が含まれていることに注意してください。 この場合、内部例外は、ランタイムが依存アセンブリを見つけることができないためにスローされた FileNotFoundException となります。

    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()
    

    Note

    この例では、アセンブリを読み込めなかったため、TypeInitializationException 例外がスローされました。 この例外は、静的コンストラクターが、構成ファイル、XML ファイル、シリアル化されたデータを含むファイルなどのデータ ファイルを開こうとして、それを見つけられない場合にもスローされる可能性があります。

正規表現マッチのタイムアウト値

正規表現パターン マッチング操作の既定のタイムアウト値は、アプリケーション ドメインごとの基準で設定できます。 タイムアウトは、AppDomain.SetData メソッドに "REGEX_DEFAULT_MATCH_TIMEOUT" プロパティの TimeSpan 値を指定することで定義されます。 時間間隔は、0 より大きく、約 24 日未満の有効な TimeSpan オブジェクトである必要があります。 これらの要件が満たされていない場合、既定のタイムアウト値を設定しようとすると、ArgumentOutOfRangeException がスローされ、これはその後 TypeInitializationException 例外にラップされます。

次の例は、"REGEX_DEFAULT_MATCH_TIMEOUT" プロパティに割り当てられた値が無効な場合にスローされる TypeInitializationException を示しています。 例外を排除するには、"REGEX_DEFAULT_MATCH_TIMEOUT" プロパティを 0 より大きく、約 24 日未満の TimeSpan 値に設定します。

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: {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()
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()

カレンダーとカルチャ データ

カレンダーのインスタンスを作成しようとして、ランタイムがそのカレンダーに対応する CultureInfo オブジェクトのインスタンスを作成できない場合は、TypeInitializationException 例外がスローされます。 この例外は、以下のカレンダー クラス コンストラクターによってスローされる可能性があります。

  • JapaneseCalendar クラスのパラメーターなしコンストラクター。
  • KoreanCalendar クラスのパラメーターなしコンストラクター。
  • TaiwanCalendar クラスのパラメーターなしコンストラクター。

これらのカルチャのカルチャ データはすべてのシステムで利用可能なはずなので、この例外に遭遇することは、あったとしてもごくまれなはずです。