leiflundgren
leiflundgren

Reputation: 2966

Create COMException from HRESULT

How do one create a COMException given a HRESULT?

I have P/Invoke:ed a win32-method which returns a HRESULT.
If it returns failure I wish to throw a COMException, with the standard error-text.
How should I do that?

  1. throw new COMException(null, hResult)

  2. COMException e = new COMException;
    e.HResult = hResult;
    throw e;

Or should I use some other method?

Upvotes: 3

Views: 1741

Answers (2)

ahawker
ahawker

Reputation: 3374

I would look into the PreserveSig field on your DllImport call. This will generate an exception for any non S_OK HRESULT returned from the function.

Upvotes: 1

svick
svick

Reputation: 244928

You should use Marshal.GetExceptionForHR() if you only want to get the exception, or Marshal.ThrowExceptionForHR() if want to throw it too.

Upvotes: 5

Related Questions