Question

I have my own exception, which been throwing on execution fail of a method (p/invoke in my case).

public PInvokeException(string methodName)
: base(String.Format(CultureInfo.CurrentCulture,
"An error occured while external method '{0}' call",
methodName)) { }

But I want to replace it with already existing. Is there in FCL something like that?

Was it helpful?

Solution

Is your caller going to take different actions based on whether you throw a PInvokeException vs. an InvalidOperationException? If so, then create a custom PInvokeException. Otherwise use InvalidOperationException and a clear error message.

See How to design Exception Hierarchies.

OTHER TIPS

There is nothing that is dedicated to PInvoke calls in the BCL. The closest that exists is Marshal.GetExceptionForHR and Marshal.GetHRForLastWin32Error. You can use the combination of these two functions to throw the appropriate exception whenever a PInvoke call fails.

Ex:

throw Marshal.GetExceptionForHR(Marshal.GetHRForLastWin32Error());

There is one: Win32Exception.

If the method you are throwing an exception from is a .Net method you should be using a custom exception (or an existing one, depending on what happened).

If you call a method on behalf of the person calling your method (or something to do with reflection - but MethodInfo.Invoke does it anyway), for example:

public void DoIt(Action action) { action(); }

You should use the TargetInvocationException exception.

If you can't handle the exception, rethrow it, or ignore it.

How about System.Runtime.InteropServices.ExternalException?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top