What exceptions can occur when using PInvoke or are all errors handled by the method return values and it is up to the developer to check and raise exceptions if needed?
4 Answers
With P/Invoke it's safe to say there are two kinds of errors you need to handle.
- Exceptions thrown by P/Invoke itself .
- Errors returned by the dll's you are invoking/
With group 1 there are a couple of exceptions that can occur (not the definitive list):
- EntryPointNotFoundException
- ExecutionEngineException
- MissingMethodException
- NotSupportedException
With group 2 you need to check the return result of your P/Invoked method/function call and act appropriately. Marshal.GetLastWin32Error() comes in handy here.
This is why it's always best to create wrapper classes for any native stuff you need to use. That way you can convert your return results to exceptions and separate your managed and native code.

- 5,017
- 1
- 23
- 20
-
SEH exceptions thrown by the DLL will also be converted into SEHException. Some standard exceptions will be converted into standard .NET exceptions instead. – poizan42 Oct 26 '19 at 19:56
I'm not sure if there is a definitive list of the exceptions that can be thrown, but I know at least the following can occur
- AccessViolationException
- StackOverflowException
- Exception when DLL named is not found. Can't remember the type off the top of my head
- OutOfMemoryException
Most of these exceptions types are not specific to PInvoke and can occur at any point in the program. The only one specific to the PInvoke call is the DLL not found exception (who's type I can't remember).

- 733,204
- 149
- 1,241
- 1,454
Also:
DllNotFoundException
BadImageFormatException
(DLL is wrong format or corrupted)MethodAccessException
(Attempt by security transparent method to call native code)

- 5,550
- 4
- 33
- 39
pinvoke also throws a MissingMethodException
on mobile devices, when the process is out of memory: http://www.tomergabel.com/NETCompactFrameworkPInvokeAndMissingMethodException.aspx

- 246,190
- 53
- 318
- 364