Reputation: 2966
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?
throw new COMException(null, hResult)
COMException e = new COMException;
e.HResult = hResult;
throw e;
Or should I use some other method?
Upvotes: 3
Views: 1741
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
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