TypeLoadException Constructeurs

Définition

Initialise une nouvelle instance de la classe TypeLoadException.Initializes a new instance of the TypeLoadException class.

Surcharges

TypeLoadException()

Initialise une nouvelle instance de la classe TypeLoadException.Initializes a new instance of the TypeLoadException class.

TypeLoadException(String)

Initialise une nouvelle instance de la classe TypeLoadException avec un message d'erreur spécifié.Initializes a new instance of the TypeLoadException class with a specified error message.

TypeLoadException(SerializationInfo, StreamingContext)

Initialise une nouvelle instance de la classe TypeLoadException avec des données sérialisées.Initializes a new instance of the TypeLoadException class with serialized data.

TypeLoadException(String, Exception)

Initialise une nouvelle instance de la classe TypeLoadException avec un message d'erreur spécifié et une référence à l'exception interne ayant provoqué cette exception.Initializes a new instance of the TypeLoadException class with a specified error message and a reference to the inner exception that is the cause of this exception.

TypeLoadException()

Initialise une nouvelle instance de la classe TypeLoadException.Initializes a new instance of the TypeLoadException class.

public:
 TypeLoadException();
public TypeLoadException ();
Public Sub New ()

Remarques

Ce constructeur initialise la Message propriété de la nouvelle instance à un message fourni par le système qui décrit l’erreur, tel que « une erreur s’est produite lors du chargement d’un type ».This constructor initializes the Message property of the new instance to a system-supplied message that describes the error, such as "A failure has occurred while loading a type." Ce message prend en compte la culture système en cours.This message takes into account the current system culture.

Le tableau suivant affiche les valeurs de propriété initiales pour une instance de TypeLoadException.The following table shows the initial property values for an instance of TypeLoadException.

PropriétéProperty ValeurValue
InnerException Référence Null (Nothing en Visual Basic).A null reference (Nothing in Visual Basic).
Message Chaîne du message d'erreur localisé.The localized error message string.

TypeLoadException(String)

Initialise une nouvelle instance de la classe TypeLoadException avec un message d'erreur spécifié.Initializes a new instance of the TypeLoadException class with a specified error message.

public:
 TypeLoadException(System::String ^ message);
public TypeLoadException (string message);
new TypeLoadException : string -> TypeLoadException
Public Sub New (message As String)

Paramètres

message
String

Message décrivant l'erreur.The message that describes the error.

Exemples

L’exemple de code suivant illustre le TypeLoadException(String) constructeur.The following code example demonstrates the TypeLoadException(String) constructor. Il contient une méthode qui génère un TypeLoadException avec un message personnalisé, et affiche le message d’erreur dans la console.It contains a method that generates a TypeLoadException with a custom message, and displays the error message to the console.

using namespace System;

class TypeLoadExceptionDemoClass
{
   public:
      static bool GenerateException()
      {
         // Throw a TypeLoadException with a custom message.
         throw gcnew TypeLoadException("This is a custom TypeLoadException error message.");
      }
};

int main()
{
   try {
      // Call a method that throws an exception.  
      TypeLoadExceptionDemoClass::GenerateException();
   }
   catch ( TypeLoadException^ e ) {
      Console::WriteLine("TypeLoadException:\n   {0}", e->Message);
   }
   catch ( Exception^ e ) 
   {
      Console::WriteLine( "Exception: \n\tError Message = {0}", e->Message );
   }

}
// The example displays the following output:
//       TypeLoadException:
//          This is a custom TypeLoadException error message.
using System;

public class Example
{
   public static void Main()
   {
      try {
         // Call a method that throws an exception.
         TypeLoadExceptionDemoClass.GenerateException();
      }
      catch (TypeLoadException e) {
         Console.WriteLine("TypeLoadException:\n   {0}", e.Message);
      }
   }
}

class TypeLoadExceptionDemoClass
{
   public static bool GenerateException()
   {
      // Throw a TypeLoadException with a custom defined message.
      throw new TypeLoadException("This is a custom TypeLoadException error message.");
   }
}
// The example displays the following output:
//       TypeLoadException:
//          This is a custom TypeLoadException error message.
Public Class Example
   Public Shared Sub Main()
      Try
         ' Call a method that throws an exception.
         TypeLoadExceptionDemoClass.GenerateException()
      Catch e As TypeLoadException
         Console.WriteLine("TypeLoadException:{0}   {1}", vbCrLf, e.Message)
      End Try
   End Sub 
End Class 

Class TypeLoadExceptionDemoClass
   Public Shared Function GenerateException() As Boolean
      ' Throw a TypeLoadException with a custom message.
      Throw New TypeLoadException("This is a custom TypeLoadException error message.")
   End Function 
End Class 
' The example displays the following output:
'       TypeLoadException:
'          This is a custom TypeLoadException error message.

Remarques

Le contenu du message paramètre doit être compréhensible par l’utilisateur.The content of the message parameter should be understandable to the user. L'appelant de ce constructeur est requis pour vérifier que cette chaîne a été localisée pour la culture système actuelle.The caller of this constructor is required to ensure that this string has been localized for the current system culture.

Le tableau suivant affiche les valeurs de propriété initiales pour une instance de TypeLoadException.The following table shows the initial property values for an instance of TypeLoadException.

PropriétéProperty ValeurValue
InnerException Référence Null (Nothing en Visual Basic).A null reference (Nothing in Visual Basic).
Message Chaîne de message d'erreur.The error message string.

TypeLoadException(SerializationInfo, StreamingContext)

Initialise une nouvelle instance de la classe TypeLoadException avec des données sérialisées.Initializes a new instance of the TypeLoadException class with serialized data.

protected:
 TypeLoadException(System::Runtime::Serialization::SerializationInfo ^ info, System::Runtime::Serialization::StreamingContext context);
protected TypeLoadException (System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context);
new TypeLoadException : System.Runtime.Serialization.SerializationInfo * System.Runtime.Serialization.StreamingContext -> TypeLoadException
Protected Sub New (info As SerializationInfo, context As StreamingContext)

Paramètres

info
SerializationInfo

Objet qui contient les données sérialisées de l'objet.The object that holds the serialized object data.

context
StreamingContext

Informations contextuelles sur la source ou la destination.The contextual information about the source or destination.

Exceptions

L’objet info est null.The info object is null.

Exemples

L’exemple suivant génère une exception et sérialise les données d’exception dans un fichier, puis Reconstitue l’exception.The following example generates an exception, and serializes the exception data to a file, and then reconstitutes the exception. Pour que cet exemple de code s’exécute, vous devez fournir le nom complet de l’assembly.For this code example to run, you must provide the fully qualified assembly name. Pour plus d’informations sur la façon d’obtenir le nom complet de l’assembly, consultez noms d’assemblys.For information about how to obtain the fully qualified assembly name, see Assembly Names.

#using <System.Runtime.Serialization.Formatters.Soap.dll>

using namespace System;
using namespace System::Reflection;
using namespace System::Runtime::Serialization;
using namespace System::Runtime::Serialization::Formatters::Soap;
using namespace System::IO;

// This class overrides the GetObjectData method and initializes
// its data with current time. 

[Serializable]
public ref class MyTypeLoadExceptionChild: public TypeLoadException
{
public:
   System::DateTime ErrorDateTime;
   MyTypeLoadExceptionChild()
   {
      ErrorDateTime = DateTime::Now;
   }

   MyTypeLoadExceptionChild( DateTime myDateTime )
   {
      ErrorDateTime = myDateTime;
   }


protected:
   MyTypeLoadExceptionChild( SerializationInfo^ sInfo, StreamingContext * sContext )
   {
      
      // Reconstitute the deserialized information into the instance.
      ErrorDateTime = sInfo->GetDateTime( "ErrorDate" );
   }


public:
   void GetObjectData( SerializationInfo^ sInfo, StreamingContext * sContext )
   {
      
      // Add a value to the Serialization information.
      sInfo->AddValue( "ErrorDate", ErrorDateTime );
   }

};

int main()
{
   
   // Load the mscorlib assembly and get a reference to it.
   // You must supply the fully qualified assembly name for mscorlib.dll here.
   Assembly^ myAssembly = Assembly::Load( "Assembly text name, Version, Culture, PublicKeyToken" );
   try
   {
      Console::WriteLine( "Attempting to load a type not present in the assembly 'mscorlib'" );
      
      // This loading of invalid type raises a TypeLoadException
      Type^ myType = myAssembly->GetType( "System::NonExistentType", true );
   }
   catch ( TypeLoadException^ ) 
   {
      
      // Serialize the exception to disk and reconstitute it back again.
      try
      {
         System::DateTime ErrorDatetime = DateTime::Now;
         Console::WriteLine( "A TypeLoadException has been raised." );
         
         // Create MyTypeLoadException instance with current time.
         MyTypeLoadExceptionChild^ myTypeLoadExceptionChild = gcnew MyTypeLoadExceptionChild( ErrorDatetime );
         IFormatter^ myFormatter = gcnew SoapFormatter;
         Stream^ myFileStream = gcnew FileStream( "typeload.xml",FileMode::Create,FileAccess::Write,FileShare::None );
         Console::WriteLine( "Serializing the TypeLoadException with DateTime as {0}", ErrorDatetime );
         
         // Serialize the MyTypeLoadException instance to a file.
         myFormatter->Serialize( myFileStream, myTypeLoadExceptionChild );
         myFileStream->Close();
         Console::WriteLine( "Deserializing the Exception." );
         myFileStream = gcnew FileStream( "typeload.xml",FileMode::Open,FileAccess::Read,FileShare::None );
         
         // Deserialize and reconstitute the instance from file.
         myTypeLoadExceptionChild = safe_cast<MyTypeLoadExceptionChild^>(myFormatter->Deserialize( myFileStream ));
         myFileStream->Close();
         Console::WriteLine( "Deserialized exception has ErrorDateTime = {0}", myTypeLoadExceptionChild->ErrorDateTime );
      }
      catch ( Exception^ e ) 
      {
         Console::WriteLine( "Exception : {0}", e->Message );
      }

   }
   catch ( Exception^ e ) 
   {
      Console::WriteLine( "Exception : {0}", e->Message );
   }

}


using System;
using System.Reflection;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Soap;
using System.Security.Permissions;
using System.IO;

class GetObjectDataDemo
{
   public static void Main()
   {
      // Get a reference to the assembly mscorlib.dll, which is always
      // loaded. (System.String is defined in mscorlib.)
      Assembly mscorlib = typeof(string).Assembly;

      try
      {
         Console.WriteLine ("Attempting to load a type not present in the assembly 'mscorlib'");
         // This loading of invalid type raises a TypeLoadException
         Type myType = mscorlib.GetType("System.NonExistentType", true);
      }
      catch (TypeLoadException)
      {
         // Serialize the exception to disk and reconstitute it.
         System.DateTime ErrorDatetime = DateTime.Now;
         Console.WriteLine("A TypeLoadException has been raised.");

         // Create MyTypeLoadException instance with current time.
         MyTypeLoadException myException = new MyTypeLoadException(ErrorDatetime);
         IFormatter myFormatter = new SoapFormatter();
         Stream myFileStream = new FileStream("typeload.xml", FileMode.Create, FileAccess.Write, FileShare.None);
         Console.WriteLine("Serializing the TypeLoadException with DateTime as " + ErrorDatetime);

         // Serialize the MyTypeLoadException instance to a file.
         myFormatter.Serialize(myFileStream, myException);
         myFileStream.Close();

         Console.WriteLine("Deserializing the Exception.");
         myFileStream = new FileStream("typeload.xml", FileMode.Open, FileAccess.Read, FileShare.None);

         // Deserialize and reconstitute the instance from file.
         myException = (MyTypeLoadException) myFormatter.Deserialize(myFileStream);
         myFileStream.Close();
         Console.WriteLine("Deserialized exception has ErrorDateTime = " + myException.ErrorDateTime);
      }
   }
}

// This class overrides the GetObjectData method and initializes
// its data with current time.

[Serializable]
public class MyTypeLoadException : TypeLoadException
{
   private System.DateTime _errorDateTime = DateTime.Now;
   public DateTime ErrorDateTime { get { return _errorDateTime; }}

   public MyTypeLoadException(DateTime myDateTime)
   {
      _errorDateTime = myDateTime;
   }

   protected MyTypeLoadException(SerializationInfo sInfo, StreamingContext sContext)
       : base(sInfo, sContext)
   {
      // Reconstitute the deserialized information into the instance.
      _errorDateTime = sInfo.GetDateTime("ErrorDate");
   }

   // GetObjectData overrides must always have a demand for SerializationFormatter.
   [SecurityPermissionAttribute(SecurityAction.Demand, SerializationFormatter=true)]
   public override void GetObjectData(SerializationInfo sInfo, StreamingContext sContext)
   {
      base.GetObjectData(sInfo, sContext);
      // Add a value to the Serialization information.
      sInfo.AddValue("ErrorDate", ErrorDateTime);
   }
}
Imports System.Reflection
Imports System.Runtime.Serialization
Imports System.Runtime.Serialization.Formatters.Soap
Imports System.Security.Permissions
Imports System.IO

Class GetObjectDataDemo

   Public Shared Sub Main()
      ' Get a reference to the assembly mscorlib.dll, which is always
      ' loaded. (System.String is defined in mscorlib.)
      Dim tString As Type = GetType(String)
      Dim mscorlib As [Assembly] = tString.Assembly

      Try
         Console.WriteLine("Attempting to load a type not present in the assembly 'mscorlib'")
         ' This loading of invalid type raises a TypeLoadException
         Dim myType As Type = mscorlib.GetType("System.NonExistentType", True)
      Catch
         ' Serialize the exception to disk and reconstitute it.
         Dim ErrorDatetime as System.DateTime = DateTime.Now
         Console.WriteLine("A TypeLoadException has been raised.")

         ' Create MyTypeLoadException instance with current time.
         Dim myException As new MyTypeLoadException(ErrorDatetime)
         Dim myFormatter as IFormatter  = new SoapFormatter()
         Dim myFileStream as Stream 
         myFileStream = New FileStream("typeload.xml", FileMode.Create, FileAccess.Write, FileShare.None)
         Console.WriteLine("Serializing the TypeLoadException with DateTime as " _
             & ErrorDatetime.ToString())

         ' Serialize the MyTypeLoadException instance to a file.
         myFormatter.Serialize(myFileStream, myException)
         myFileStream.Close()

         Console.WriteLine("Deserializing the Exception.")
         myFileStream = New FileStream("typeload.xml", FileMode.Open, FileAccess.Read, FileShare.None)

         ' Deserialize and reconstitute the instance from file.
         myException = CType(myFormatter.Deserialize(myFileStream), MyTypeLoadException)
         myFileStream.Close()
         Console.WriteLine("Deserialized exception has ErrorDateTime = " + myException.ErrorDateTime.ToString())
      End Try
   End Sub
End Class

' This class overrides the GetObjectData method and initializes
' its data with current time. 
<Serializable()> _
Public Class MyTypeLoadException
   Inherits TypeLoadException

   Private _errorDateTime As System.DateTime = DateTime.Now
   Public ReadOnly Property ErrorDateTime As DateTime
      Get
         Return _errorDateTime
      End Get
   End Property

   Public Sub New(myDateTime As DateTime)
      _errorDateTime = myDateTime
   End Sub

   Protected Sub New(sInfo As SerializationInfo, sContext As StreamingContext)
      MyBase.New(sInfo, sContext)
      ' Reconstitute the deserialized information into the instance.
      _errorDateTime = sInfo.GetDateTime("ErrorDate")
   End Sub

   ' GetObjectData overrides must always have a demand for SerializationFormatter.
   <SecurityPermissionAttribute(SecurityAction.Demand, SerializationFormatter:=true)> _
   Public Overrides Sub GetObjectData(sInfo As SerializationInfo, sContext As StreamingContext)
      MyBase.GetObjectData(sInfo, sContext)
      ' Add a value to the Serialization information.
      sInfo.AddValue("ErrorDate", ErrorDateTime)
   End Sub

End Class

Remarques

Ce constructeur est appelé lors de la désérialisation afin de reconstituer l'objet exception transmis sur un flux.This constructor is called during deserialization to reconstitute the exception object transmitted over a stream. Pour plus d’informations, consultez sérialisation XML et SOAP.For more information, see XML and SOAP Serialization.

Voir aussi

TypeLoadException(String, Exception)

Initialise une nouvelle instance de la classe TypeLoadException avec un message d'erreur spécifié et une référence à l'exception interne ayant provoqué cette exception.Initializes a new instance of the TypeLoadException class with a specified error message and a reference to the inner exception that is the cause of this exception.

public:
 TypeLoadException(System::String ^ message, Exception ^ inner);
public TypeLoadException (string message, Exception inner);
new TypeLoadException : string * Exception -> TypeLoadException
Public Sub New (message As String, inner As Exception)

Paramètres

message
String

Message d'erreur qui explique la raison de l'exception.The error message that explains the reason for the exception.

inner
Exception

Exception ayant provoqué l'exception actuelle.The exception that is the cause of the current exception. Si le paramètre inner n'est pas null, l'exception actuelle est levée dans un bloc catch qui gère l'exception interne.If the inner parameter is not null, the current exception is raised in a catch block that handles the inner exception.

Exemples

L’exemple de code suivant illustre le TypeLoadException(String, Exception) constructeur.The following code example demonstrates the TypeLoadException(String, Exception) constructor. Il contient une méthode qui génère un TypeLoadException , intercepte cette exception et lève une nouvelle TypeLoadException avec un message personnalisé, y compris l’original TypeLoadException comme exception interne.It contains a method that generates a TypeLoadException, catches that exception, and throws a new TypeLoadException with a custom message, including the original TypeLoadException as the inner exception.

using namespace System;
using namespace System::Runtime::InteropServices;
ref class TypeLoadExceptionDemoClass
{
public:

   // A call to this method will raise a TypeLoadException.

   [DllImport("NonExistentDLL.DLL",EntryPoint="MethodNotExists")]
   static void NonExistentMethod();
   static void GenerateException()
   {
      try
      {
         NonExistentMethod();
      }
      catch ( TypeLoadException^ e ) 
      {
         
         // Rethrow exception with the exception as inner exception
         throw gcnew TypeLoadException( "This exception was raised due to a call to an invalid method.",e );
      }

   }

};

int main()
{
   Console::WriteLine( "Calling a method in a non-existent DLL which triggers a TypeLoadException." );
   try
   {
      TypeLoadExceptionDemoClass::GenerateException();
   }
   catch ( TypeLoadException^ e ) 
   {
      Console::WriteLine( "TypeLoadException: \n\tError Message = {0}", e->Message );
      Console::WriteLine( "TypeLoadException: \n\tInnerException Message = {0}", e->InnerException->Message );
   }
   catch ( Exception^ e ) 
   {
      Console::WriteLine( "Exception: \n\tError Message = {0}", e->Message );
   }

}


using System;
using System.Runtime.InteropServices;

public class TypeLoadException_Constructor3
{
   public static void Main()
   {
      Console.WriteLine("Calling a method in a non-existent DLL which triggers a TypeLoadException.");
      try
      {
         TypeLoadExceptionDemoClass.GenerateException();
      }
      catch (TypeLoadException e)
      {
         Console.WriteLine ("TypeLoadException: \n\tError Message = " + e.Message);
         Console.WriteLine ("TypeLoadException: \n\tInnerException Message = " + e.InnerException.Message );
      }
      catch (Exception e)
      {
         Console.WriteLine ("Exception: \n\tError Message = " + e.Message);
      }
   }
}

class TypeLoadExceptionDemoClass
{
   // A call to this method will raise a TypeLoadException.
   [DllImport("NonExistentDLL.DLL", EntryPoint="MethodNotExists")]
   public static extern void NonExistentMethod();

   public static void GenerateException()
   {
      try
      {
         NonExistentMethod();
      }
      catch (TypeLoadException e)
      {
         // Rethrow exception with the exception as inner exception
         throw new TypeLoadException("This exception was raised due to a call to an invalid method.", e);
      }
   }
}
Imports System.Runtime.InteropServices

Public Class TypeLoadException_Constructor3
   Public Shared Sub Main()
      Console.WriteLine("Calling a method in a non-existent DLL which triggers a TypeLoadException.")
      Try
         TypeLoadExceptionDemoClass.GenerateException()
      Catch e As TypeLoadException
         Console.WriteLine(("TypeLoadException: " + ControlChars.Cr + ControlChars.Tab + "Error Message = " + e.Message))
         Console.WriteLine(("TypeLoadException: " + ControlChars.Cr + ControlChars.Tab + "InnerException Message = " + e.InnerException.Message))
      Catch e As Exception
         Console.WriteLine(("Exception: " + ControlChars.Cr + ControlChars.Tab + "Error Message = " + e.Message))
      End Try
   End Sub
End Class

Class TypeLoadExceptionDemoClass
   ' A call to this method will raise a TypeLoadException.
   Public Declare Sub NonExistentMethod Lib "NonExistentDLL.DLL" Alias "MethodNotExists" ()

   Public Shared Sub GenerateException()
      Try
         NonExistentMethod()
      Catch e As TypeLoadException
         ' Rethrow exception with the exception as inner exception
         Throw New TypeLoadException("This exception was raised due to a call to an invalid method.", e)
      End Try
   End Sub
End Class

Remarques

Une exception qui est levée en conséquence directe d'une exception précédente peut contenir une référence à l'exception précédente dans la propriété InnerException.An exception that is thrown as a direct result of a previous exception can include a reference to the previous exception in the InnerException property. La propriété InnerException retourne la valeur passée au constructeur ou la valeur null si la propriété InnerException ne fournit pas la valeur d'exception interne au constructeur.The InnerException property returns the same value that is passed into the constructor, or null if the InnerException property does not supply the inner exception value to the constructor.

Le tableau suivant affiche les valeurs de propriété initiales pour une instance de TypeLoadException.The following table shows the initial property values for an instance of TypeLoadException.

PropriétéProperty ValueValue
InnerException La référence à l'exception interne.The inner exception reference.
Message Chaîne de message d'erreur.The error message string.

Voir aussi

S’applique à