Remarque
L’accès à cette page nécessite une autorisation. Vous pouvez essayer de vous connecter ou de modifier des répertoires.
L’accès à cette page nécessite une autorisation. Vous pouvez essayer de modifier des répertoires.
Les méthodes COM signalent des erreurs en retournant des HRESULT ; les méthodes .NET les signalent en levant des exceptions. Le runtime gère la transition entre les deux. Chaque classe d’exception dans .NET est mappée à un HRESULT.
Les classes d’exception définies par l’utilisateur peuvent spécifier tout ce qui convient à HRESULT. Ces classes d’exception peuvent modifier dynamiquement le HRESULT à retourner lorsque l’exception est générée en définissant le HResult champ sur l’objet d’exception. Des informations supplémentaires sur l’exception sont fournies au client via l’interfaceIErrorInfo, qui est implémentée sur l’objet .NET dans le processus non managé.
Si vous créez une classe qui s’étend System.Exception, vous devez définir le champ HRESULT pendant la construction. Sinon, la classe de base affecte la valeur HRESULT. Vous pouvez mapper de nouvelles classes d’exception à un HRESULT existant en fournissant la valeur dans le constructeur de l’exception.
Notez que l’environnement d’exécution ignore parfois un HRESULT dans les cas où un IErrorInfo est présent dans le thread. Ce comportement peut se produire dans les cas où le HRESULT et le IErrorInfo ne représentent pas la même erreur.
Pour créer une classe d’exception et la mapper à un HRESULT
Utilisez le code suivant pour créer une classe d’exception appelée
NoAccessExceptionet la mapper à HRESULTE_ACCESSDENIED.Class NoAccessException : public ApplicationException { NoAccessException () { HResult = E_ACCESSDENIED; } } CMyClass::MethodThatThrows { throw new NoAccessException(); }
Vous pouvez rencontrer un programme (dans n’importe quel langage de programmation) qui utilise du code managé et non managé en même temps. Par exemple, le marshaler personnalisé dans l’exemple de code suivant utilise la Marshal.ThrowExceptionForHR(int HResult) méthode pour lever une exception avec une valeur HRESULT spécifique. La méthode recherche HRESULT et génère le type d’exception approprié. Par exemple, HRESULT dans le fragment de code suivant génère ArgumentException.
CMyClass::MethodThatThrows
{
Marshal.ThrowExceptionForHR(COR_E_ARGUMENT);
}
Le tableau suivant fournit les mappages courants de HRESULT à sa classe d’exception comparable dans .NET. Les valeurs HRESULT sans mappages explicites sont mappées à COMException. La correspondance complète et à jour est disponible dans le référentiel dotnet/runtime.
| HRESULT | exception .NET |
|---|---|
COR_E_APPLICATION |
ApplicationException |
COR_E_ARGUMENT ou E_INVALIDARG |
ArgumentException |
COR_E_ARGUMENTOUTOFRANGE |
ArgumentOutOfRangeException |
COR_E_ARITHMETIC or ERROR_ARITHMETIC_OVERFLOW |
ArithmeticException |
COR_E_ARRAYTYPEMISMATCH |
ArrayTypeMismatchException |
COR_E_BADIMAGEFORMAT or ERROR_BAD_FORMAT |
BadImageFormatException |
COR_E_DIRECTORYNOTFOUND or ERROR_PATH_NOT_FOUND |
DirectoryNotFoundException |
COR_E_DIVIDEBYZERO |
DivideByZeroException |
COR_E_DUPLICATEWAITOBJECT |
DuplicateWaitObjectException |
COR_E_ENDOFSTREAM |
EndOfStreamException |
COR_E_ENTRYPOINTNOTFOUND |
EntryPointNotFoundException |
COR_E_EXCEPTION |
Exception |
COR_E_EXECUTIONENGINE |
ExecutionEngineException |
COR_E_FIELDACCESS |
FieldAccessException |
COR_E_FILENOTFOUND or ERROR_FILE_NOT_FOUND |
FileNotFoundException |
COR_E_FORMAT |
FormatException |
COR_E_INDEXOUTOFRANGE |
IndexOutOfRangeException |
COR_E_INVALIDCAST or E_NOINTERFACE |
InvalidCastException |
COR_E_INVALIDFILTERCRITERIA |
InvalidFilterCriteriaException |
COR_E_INVALIDOPERATION |
InvalidOperationException |
COR_E_IO |
IOException |
COR_E_MEMBERACCESS |
AccessException |
COR_E_METHODACCESS |
MethodAccessException |
COR_E_MISSINGFIELD |
MissingFieldException |
COR_E_MISSINGMANIFESTRESOURCE |
MissingManifestResourceException |
COR_E_MISSINGMEMBER |
MissingMemberException |
COR_E_MISSINGMETHOD |
MissingMethodException |
COR_E_NOTFINITENUMBER |
NotFiniteNumberException |
E_NOTIMPL |
NotImplementedException |
COR_E_NOTSUPPORTED |
NotSupportedException |
COR_E_NULLREFERENCE orE_POINTER |
NullReferenceException |
COR_E_OUTOFMEMORY orE_OUTOFMEMORY |
OutOfMemoryException |
COR_E_OVERFLOW |
OverflowException |
COR_E_PATHTOOLONG or ERROR_FILENAME_EXCED_RANGE |
PathTooLongException |
COR_E_RANK |
RankException |
COR_E_REFLECTIONTYPELOAD |
ReflectionTypeLoadException |
COR_E_SECURITY |
SecurityException |
COR_E_SERIALIZATION |
SerializationException |
COR_E_STACKOVERFLOW orERROR_STACK_OVERFLOW |
StackOverflowException |
COR_E_SYNCHRONIZATIONLOCK |
SynchronizationLockException |
COR_E_SYSTEM |
SystemException |
COR_E_TARGET |
TargetException |
COR_E_TARGETINVOCATION |
TargetInvocationException |
COR_E_TARGETPARAMCOUNT |
TargetParameterCountException |
COR_E_THREADINTERRUPTED |
ThreadInterruptedException |
COR_E_THREADSTATE |
ThreadStateException |
COR_E_TYPELOAD |
TypeLoadException |
COR_E_TYPEINITIALIZATION |
TypeInitializationException |
COR_E_VERIFICATION |
VerificationException |
Pour récupérer des informations d’erreur étendues, le client géré doit examiner les champs de l’objet d’exception généré. Pour que l’objet d’exception fournisse des informations utiles sur une erreur, l’objet COM doit implémenter l’interface IErrorInfo . L’environnement d’exécution utilise les informations fournies par IErrorInfo pour initialiser l’objet d’exception.
Si l’objet COM ne prend pas en charge IErrorInfo, le runtime initialise un objet d’exception avec des valeurs par défaut. Le tableau suivant répertorie chaque champ associé à un objet d’exception et identifie la source des informations par défaut lorsque l’objet COM prend en charge IErrorInfo.
Notez que l’environnement d’exécution ignore parfois un HRESULT dans les cas où un IErrorInfo est présent sur le thread. Ce comportement peut se produire dans les cas où le HRESULT et le IErrorInfo ne représentent pas la même erreur.
| Champ d’exception | Source d’informations de COM |
|---|---|
ErrorCode |
HRESULT retourné par l’appel. |
HelpLink |
Si IErrorInfo->HelpContext est différent de zéro, la chaîne est formée par concaténation de IErrorInfo->GetHelpFile, de « # » et de IErrorInfo->GetHelpContext. Sinon, la chaîne est retournée à partir de IErrorInfo->GetHelpFile. |
InnerException |
Toujours une référence Null (Nothingdans Visual Basic). |
Message |
Chaîne renvoyée par IErrorInfo->GetDescription. |
Source |
Chaîne renvoyée par IErrorInfo->GetSource. |
StackTrace |
Trace de la pile. |
TargetSite |
Nom de la méthode qui a retourné le HRESULT défaillant. |
Les champs d’exception, tels que Message, Sourceet StackTrace ne sont pas disponibles pour le StackOverflowException.