views:

149

answers:

4

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?

+1  A: 

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());
JaredPar
Maybe some exception not directly connected with p/invoke failure, but just method call fail? Nothing like that?
abatishchev
+1  A: 

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.

Jonathan C Dickinson
+2  A: 

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.

John Saunders
+1  A: 

How about System.Runtime.InteropServices.ExternalException?

leppie