TypeInitializationException Classe
Definição
Importante
Algumas informações se referem a produtos de pré-lançamento que podem ser substancialmente modificados antes do lançamento. A Microsoft não oferece garantias, expressas ou implícitas, das informações aqui fornecidas.
A exceção gerada como um wrapper em torno da exceção gerada pelo inicializador de classe. Essa classe não pode ser herdada.
public ref class TypeInitializationException sealed : Exception
public ref class TypeInitializationException sealed : SystemException
public sealed class TypeInitializationException : Exception
public sealed class TypeInitializationException : SystemException
[System.Serializable]
public sealed class TypeInitializationException : SystemException
[System.Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class TypeInitializationException : SystemException
type TypeInitializationException = class
inherit Exception
type TypeInitializationException = class
inherit SystemException
[<System.Serializable>]
type TypeInitializationException = class
inherit SystemException
[<System.Serializable>]
[<System.Runtime.InteropServices.ComVisible(true)>]
type TypeInitializationException = class
inherit SystemException
Public NotInheritable Class TypeInitializationException
Inherits Exception
Public NotInheritable Class TypeInitializationException
Inherits SystemException
- Herança
- Herança
- Atributos
Comentários
Quando um inicializador de classe falha ao inicializar um tipo, um TypeInitializationException é criado e uma referência à exceção lançada pelo inicializador de classe do tipo é passada. A InnerException propriedade de TypeInitializationException contém a exceção subjacente.
Normalmente, a TypeInitializationException exceção reflete uma condição catastrófica (o runtime não pode criar uma instância de um tipo) que impede que um aplicativo continue. Mais comumente, o TypeInitializationException é gerado em resposta a alguma alteração no ambiente de execução do aplicativo. Consequentemente, a exceção não deve ser tratada em um bloco try/catch, exceto possivelmente para solucionar problemas de código de depuração. Em vez disso, a causa da exceção deve ser investigada e eliminada.
TypeInitializationException usa o HRESULT COR_E_TYPEINITIALIZATION, que tem o valor 0x80131534.
Para obter uma lista de valores de propriedade iniciais de uma instância de TypeInitializationException, consulte os construtores de TypeInitializationException.
As seções a seguir descrevem algumas das situações em que uma TypeInitializationException exceção é gerada.
Construtores estáticos
Um construtor estático, se existir, será chamado automaticamente pelo runtime antes de criar uma nova instância de um tipo. Construtores estáticos podem ser definidos explicitamente por um desenvolvedor. Se um construtor estático não for definido explicitamente, os compiladores criarão automaticamente um para inicializar qualquer static membro (em C# ou F#) ou Shared (no Visual Basic) do tipo. Para obter mais informações sobre construtores estáticos, consulte Construtores Estáticos.
Mais comumente, uma TypeInitializationException exceção é gerada quando um construtor estático não consegue instanciar um tipo. A InnerException propriedade indica por que o construtor estático não pôde instanciar o tipo. Algumas das causas mais comuns de uma TypeInitializationException exceção são:
Uma exceção sem tratamento em um construtor estático
Se uma exceção for lançada em um construtor estático, essa exceção será encapsulada em uma TypeInitializationException exceção e o tipo não poderá ser instanciado.
O que geralmente dificulta a solução de problemas dessa exceção é que construtores estáticos nem sempre são definidos explicitamente no código-fonte. Um construtor estático existe em um tipo se:
Ele foi explicitamente definido como um membro de um tipo.
O tipo tem
staticvariáveis (em C# ou F#) ouShared(no Visual Basic) declaradas e inicializadas em uma única instrução. Nesse caso, o compilador de linguagem gera um construtor estático para o tipo. Por exemplo, quando os compiladores C# e VB compilam o exemplo a seguir, eles geram o IL para um construtor estático semelhante a este:.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
O exemplo a seguir mostra uma TypeInitializationException exceção gerada por um construtor estático gerado pelo compilador. A
Exampleclasse inclui umstaticcampo (em C#) ouShared(no Visual Basic) do tipoTestClassque é instanciado passando um valor de 3 para seu construtor de classe. Esse valor, no entanto, é ilegal; somente valores de 0 ou 1 são permitidos. Como resultado, o construtor da classeTestClasslança um ArgumentOutOfRangeException. Como essa exceção não é tratada, ela é encapsulada em uma TypeInitializationException exceção.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)) End If 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()A mensagem de exceção exibe informações sobre a InnerException propriedade.
Falta um assembly ou um arquivo de dados
Uma causa comum de uma TypeInitializationException exceção é que um assembly ou arquivo de dados que estava presente nos ambientes de desenvolvimento e teste de um aplicativo está ausente de seu ambiente de runtime. Por exemplo, você pode compilar o exemplo a seguir em um assembly chamado Missing1a.dll usando esta sintaxe de linha de comando:
csc -t:library Missing1a.csfsc --target:library Missing1a.fsvbc Missing1a.vb -t:libraryusing 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() = firstUsePublic 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 ClassEm seguida, você pode compilar o exemplo a seguir para um executável chamado Missing1.exe incluindo uma referência a Missing1a.dll:
csc Missing1.cs /r:Missing1a.dllvbc Missing1.vb /r:Missing1a.dllNo entanto, se você renomear, mover ou excluir Missing1a.dll e executar o exemplo, ele gerará uma TypeInitializationException exceção e exibirá a saída mostrada no exemplo. Observe que a mensagem de exceção inclui informações sobre a InnerException propriedade. Nesse caso, a exceção interna é uma FileNotFoundException que é lançada porque o runtime não consegue encontrar o assembly dependente.
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
Neste exemplo, uma TypeInitializationException exceção foi gerada porque não foi possível carregar um assembly. A exceção também poderá ser gerada se um construtor estático tentar abrir um arquivo de dados, como um arquivo de configuração, um arquivo XML ou um arquivo que contém dados serializados, que ele não pode encontrar.
Valores de tempo limite para correspondência de expressão regular
Você pode definir o valor de tempo limite padrão para uma operação de comparação de padrões de expressão regular por domínio de aplicativo. O tempo limite é definido por uma especificação de um TimeSpan valor para a propriedade "REGEX_DEFAULT_MATCH_TIMEOUT" para o AppDomain.SetData método. O intervalo de tempo deve ser um objeto válido TimeSpan maior que zero e menor que aproximadamente 24 dias. Se esses requisitos não forem atendidos, a tentativa de definir o valor de tempo limite padrão gerará um ArgumentOutOfRangeException, que, por sua vez, é encapsulado em uma TypeInitializationException exceção.
O exemplo a seguir mostra o TypeInitializationException que é gerado quando o valor atribuído à propriedade "REGEX_DEFAULT_MATCH_TIMEOUT" é inválido. Para eliminar a exceção, defina a propriedade "REGEX_DEFAULT_MATCH_TIMEOUT" como um TimeSpan valor maior que zero e menor que aproximadamente 24 dias.
using System;
using System.Text.RegularExpressions;
using static System.Net.Mime.MediaTypeNames;
public class RegexEx1
{
public static void Run()
{
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 'AppDomain data 'REGEX_DEFAULT_MATCH_TIMEOUT' contains the invalid value or object
// '-00:00:02' 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, CultureInfo culture)
// at RegexEx1.Run()
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()
Calendários e dados culturais
Se você tentar instanciar um calendário, mas o runtime não conseguir instanciar o CultureInfo objeto que corresponde a esse calendário, ele gerará uma TypeInitializationException exceção. Essa exceção pode ser gerada pelos seguintes construtores de classe de calendário:
- O construtor sem parâmetros da JapaneseCalendar classe.
- O construtor sem parâmetros da KoreanCalendar classe.
- O construtor sem parâmetros da TaiwanCalendar classe.
Como os dados culturais dessas culturas devem estar disponíveis em todos os sistemas, você raramente deve, se nunca, encontrar essa exceção.
Construtores
| Nome | Description |
|---|---|
| TypeInitializationException(String, Exception) |
Inicializa uma nova instância da classe com a mensagem de TypeInitializationException erro padrão, o nome do tipo especificado e uma referência à exceção interna que é a causa raiz dessa exceção. |
Propriedades
| Nome | Description |
|---|---|
| Data |
Obtém uma coleção de pares chave/valor que fornecem informações adicionais definidas pelo usuário sobre a exceção. (Herdado de Exception) |
| HelpLink |
Obtém ou define um link para o arquivo de ajuda associado a essa exceção. (Herdado de Exception) |
| HResult |
Obtém ou define HRESULT, um valor numérico codificado atribuído a uma exceção específica. (Herdado de Exception) |
| InnerException |
Obtém a Exception instância que causou a exceção atual. (Herdado de Exception) |
| Message |
Obtém uma mensagem que descreve a exceção atual. (Herdado de Exception) |
| Source |
Obtém ou define o nome do aplicativo ou do objeto que causa o erro. (Herdado de Exception) |
| StackTrace |
Obtém uma representação de cadeia de caracteres dos quadros imediatos na pilha de chamadas. (Herdado de Exception) |
| TargetSite |
Obtém o método que gera a exceção atual. (Herdado de Exception) |
| TypeName |
Obtém o nome totalmente qualificado do tipo que não é inicializado. |
Métodos
| Nome | Description |
|---|---|
| Equals(Object) |
Determina se o objeto especificado é igual ao objeto atual. (Herdado de Object) |
| GetBaseException() |
Quando substituído em uma classe derivada, retorna a Exception causa raiz de uma ou mais exceções subsequentes. (Herdado de Exception) |
| GetHashCode() |
Serve como a função de hash padrão. (Herdado de Object) |
| GetObjectData(SerializationInfo, StreamingContext) |
Obsoleto.
Define o SerializationInfo objeto com o nome do tipo e informações adicionais de exceção. |
| GetType() |
Obtém o tipo de runtime da instância atual. (Herdado de Exception) |
| MemberwiseClone() |
Cria uma cópia superficial do Objectatual. (Herdado de Object) |
| ToString() |
Cria e retorna uma representação de cadeia de caracteres da exceção atual. (Herdado de Exception) |
Eventos
| Nome | Description |
|---|---|
| SerializeObjectState |
Obsoleto.
Ocorre quando uma exceção é serializada para criar um objeto de estado de exceção que contém dados serializados sobre a exceção. (Herdado de Exception) |