.NET Framework Class Library COMException Class The exception that is thrown when an unrecognized HRESULT is returned from a COM method call.

Inheritance Hierarchy
Namespace:
System.Runtime.InteropServices
Assembly:
mscorlib (in mscorlib.dll)

Syntax
<SerializableAttribute> _
<ComVisibleAttribute(True)> _
Public Class COMException _
Inherits ExternalException
[SerializableAttribute]
[ComVisibleAttribute(true)]
public class COMException : ExternalException
[SerializableAttribute]
[ComVisibleAttribute(true)]
public ref class COMException : public ExternalException
[<SerializableAttribute>]
[<ComVisibleAttribute(true)>]
type COMException =
class
inherit ExternalException
end
The COMException type exposes the following members.

Constructors

Methods

Events
|
| Name | Description |
|---|
.gif) | SerializeObjectState | Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.) | Top

Remarks
The common language runtime transforms well-known HRESULTs to.NET exceptions, enabling COM objects to return meaningful error information to managed clients. The HRESULT to exception mapping also works in the other direction by returning specific HRESULTs to unmanaged clients. For mapping details, see How to: Map HRESULTs and Exceptions. When the runtime encounters an unfamiliar HRESULT (an HRESULT that lacks a specific, corresponding exception), it throws an instance of the COMException class. This all-purpose exception exposes the same members as any exception, and includes a public ErrorCode property that contains the HRESULT returned by the callee. If an error message is available to the runtime (obtained from the IErrorInfo interface or the Err object in Visual Basic, or in some cases from the operating system), the message is returned to the caller. However, if the COM component developer fails to include an error message, the runtime returns the eight-digit HRESULT in place of a message string. Having an HRESULT allows the caller to determine the cause of the generic exception. Although you can use the COMException class to return specific HRESULTs to unmanaged clients, throwing a specific.NET exception is better than using a generic exception. Consider that managed clients as well as unmanaged clients can use your.NET object, and throwing an HRESULT to a managed caller is less comprehendible than throwing an exception.

Version Information
.NET FrameworkSupported in: 4, 3.5, 3.0, 2.0, 1.1, 1.0 .NET Framework Client ProfileSupported in: 4, 3.5 SP1

Platforms
Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role not supported), Windows Server 2003 SP2
The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

Thread Safety
Any public static ( Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

See Also
|
Biblioteca de clases de .NET Framework COMException (Clase) Excepción que se produce cuando se devuelve un valor HRESULT no reconocido desde una llamada de método COM.

Jerarquía de herencia
Espacio de nombres:
System.Runtime.InteropServices
Ensamblado:
mscorlib (en mscorlib.dll)

Sintaxis
<SerializableAttribute> _
<ComVisibleAttribute(True)> _
Public Class COMException _
Inherits ExternalException
[SerializableAttribute]
[ComVisibleAttribute(true)]
public class COMException : ExternalException
[SerializableAttribute]
[ComVisibleAttribute(true)]
public ref class COMException : public ExternalException
[<SerializableAttribute>]
[<ComVisibleAttribute(true)>]
type COMException =
class
inherit ExternalException
end
El tipo COMException expone los siguientes miembros.

Constructores

Métodos

Eventos
|
| Nombre | Descripción |
|---|
.gif) | SerializeObjectState | Se produce cuando se serializa una excepción para crear un objeto de estados de excepción que contiene datos serializados sobre la excepción. (Se hereda de Exception). | Arriba

Comentarios
Common Language Runtime transforma los valores HRESULT conocidos en excepciones de .NET, lo que permite que los objetos COM devuelvan información de error significativa a los clientes administrados. La asignación de valores HRESULT a excepciones también funciona en la otra dirección, mediante la devolución de valores HRESULT específicos a los clientes no administrados. Para obtener información detallada sobre las asignaciones, vea Cómo: Asignar resultados HRESULT y excepciones. Cuando el motor en tiempo de ejecución encuentra un valor HRESULT desconocido (un valor HRESULT que carece de una excepción específica correspondiente), genera una instancia de la clase COMException. Esta excepción, válida para cualquier propósito, expone los mismos miembros que cualquier excepción e incluye una propiedad ErrorCode pública que contiene el valor HRESULT devuelto por el destinatario de la llamada. Si hay un mensaje de error disponible para el motor en tiempo de ejecución (que se ha obtenido a partir la interfaz IErrorInfo o del objeto Err de Visual Basic o, en algunos casos, del sistema operativo), el mensaje se devuelve al llamador. Sin embargo, si el desarrollador del componente COM no incluye un mensaje de error, el motor en tiempo de ejecución devuelve el valor HRESULT de ocho dígitos en lugar de una cadena de mensaje. El hecho de disponer de un valor HRESULT permite al llamador determinar la causa de la excepción genérica. Aunque se puede utilizar la clase COMException para devolver valores HRESULT específicos a los clientes no administrados, es mejor producir una excepción específica de .NET que utilizar una excepción genérica. Hay que tener en cuenta que tanto los clientes administrados como los no administrados pueden utilizar el objeto .NET, y que lanzar un valor HRESULT a un llamador administrado es menos lógico que producir una excepción.

Información de versión
.NET FrameworkCompatible con: 4, 3.5, 3.0, 2.0, 1.1, 1.0 .NET Framework Client ProfileCompatible con: 4, 3.5 SP1

Plataformas
Windows 7, Windows Vista SP1 o posterior, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (no se admite Server Core), Windows Server 2008 R2 (se admite Server Core con SP1 o posterior), Windows Server 2003 SP2
.NET Framework no admite todas las versiones de todas las plataformas. Para obtener una lista de las versiones compatibles, vea Requisitos de sistema de .NET Framework.

Seguridad para subprocesos
Todos los miembros static ( Shared en Visual Basic) públicos de este tipo son seguros para la ejecución de subprocesos. No se garantiza que los miembros de instancias sean seguros para la ejecución de subprocesos.

Vea también
|