Alex Rivera | Logout

How can I throw an Exception with a certain HResult?

Asked 2012-06-22T14:37:46.830
17

I want to test the following code:

private bool TestException(Exception ex)
{
    if ((Marshal.GetHRForException(ex) & 0xFFFF) == 0x4005)
    {
        return true;
    }
    return false;
}

I'd like to set up the Exception object somehow to return the correct HResult, but I can't see a field in the Exception class which allows this.

How would I do this?

Edit
Report

1 Answer

23

I found three ways to do this:

  1. Use the System.Runtime.InteropServices.ExternalException class, passing in the error code as a parameter:

    var ex = new ExternalException("-", 0x4005);
    

    Thanks to @HansPassant for his comment explaining this.

  2. Pass a mock exception using inheritance to access a protected field:

    private class MockException : Exception
    {
        public MockException() { HResult = 0x4005; }
    }
    
    var ex = new MockException();
    
  3. Use .NET Reflection to set the underlying field:

    BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic;
    FieldInfo hresultFieldInfo = typeof(Exception).GetField("_HResult", flags);
    
    var ex = new Exception();
    hresultFieldInfo.SetValue(ex, 0x4005);
    

Passing any one of these exceptions to the method in the question, will result in that method returning true. I suspect the first method is most useful.

answered 2012-06-22T15:35:14.633

Your Answer