Skip to content

Title: NullReferenceException in ComInterop.ExcepInfo when GetExceptionForHR returns null #117568

@ish-1313

Description

@ish-1313

Description

If errorCode is a non-failing HRESULT, this will crash.

int errorCode = (scode != 0) ? scode : wCode;
Exception exception = Marshal.GetExceptionForHR(errorCode);
string message = ConvertAndFreeBstr(ref bstrDescription);
if (message != null)
{
// If we have a custom message, create a new Exception object with the message set correctly.
// We need to create a new object because "exception.Message" is a read-only property.
if (exception is COMException)
{
exception = new COMException(message, errorCode);
}
else
{
Type exceptionType = exception.GetType();
ConstructorInfo ctor = exceptionType.GetConstructor(new Type[] { typeof(string) });
if (ctor != null)
{
exception = (Exception)ctor.Invoke(new object[] { message });
}
}
}

.net 9.05
windows 22h2 (19045.5965)

Reproduction Steps

Repro:

  1. Call any COM method returning:
    • `HRESULT =custom code
    • bstrDescription = valid message

from GetExceptionForHR docs
"Returns
Exception
An object that represents the converted HRESULT, or null if the HRESULT value doesn't represent an error code (for example, S_OK or S_FALSE)."

Expected behavior

COMException` with the message

Actual behavior

Marshal.GetExceptionForHR() returns null (per docs, since HRESULT is unmapped)

ComInterop crashes with NullReferenceException at ex.GetType()

Regression?

No response

Known Workarounds

No response

Configuration

.NET 9.0.5

Windows 10 22H2 (19045.5965)

Other information

No response

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    Status

    No status

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions