次の方法で共有


System.TypeInitializationException クラス

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

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

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

TypeInitializationException は、値が0x80131534を持つ HRESULT COR_E_TYPEINITIALIZATIONを使用します。

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

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

静的コンストラクター

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

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

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

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

    多くの場合、この例外のトラブルシューティングが困難になるのは、静的コンストラクターが必ずしもソース コードで明示的に定義されるとは限らないということです。 静的コンストラクターは、次の場合に型に存在します。

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

    • 型には、1 つのステートメントで宣言および初期化される static (C# または F#) または Shared (Visual Basic の場合) があります。 この場合、言語コンパイラは型の静的コンストラクターを生成します。 IL 逆アセンブラーなどのユーティリティを使用して検査できます。 たとえば、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 をクラス コンストラクターに渡すことによってインスタンス化されるTestClass型のstatic (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()
    

    この例では、アセンブリを読み込めなかったため、 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: {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()

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

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

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

これらのカルチャのカルチャ データはすべてのシステムで使用できる必要があるため、この例外が発生することはめったにありません。