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?
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.
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.
HRESULT is a computer programming data type that represents the completion status of a function.
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.
I found three ways to do this:
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.
Pass a mock exception using inheritance to access a protected field:
private class MockException : Exception
{
public MockException() { HResult = 0x4005; }
}
var ex = new MockException();
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With