Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I throw an Exception with a certain HResult?

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?

like image 555
g t Avatar asked Jun 22 '12 14:06

g t


People also ask

How do you throw a specific exception?

Throwing an exception is as simple as using the "throw" statement. You then specify the Exception object you wish to throw. Every Exception includes a message which is a human-readable error description. It can often be related to problems with user input, server, backend, etc.

What does exception from HRESULT mean?

Each exception is mapped to a distinct HRESULT. When managed code throws an exception, the runtime passes the HRESULT to the COM client. When unmanaged code returns an error, the HRESULT is converted to an exception, which is then thrown by the runtime.

What is Hresult in exception C#?

HRESULT is a computer programming data type that represents the completion status of a function.

How do you throw an exception in Visual Basic?

By using a throw statement inside a catch block, we can change the resulting exception. You should throw exceptions only when an unexpected or invalid activity occurs that prevents a method from completing its normal function. You can throw any type of Throwable object using the keyword throw.


1 Answers

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.

like image 112
g t Avatar answered Oct 05 '22 18:10

g t