P/Invoke Exceptions

Chapter 7, “Leveraging Existing Code—P/Invoke,” dealt with calls into unmanaged code using P/Invoke. Next, you will look specifically at what happens to exceptions that are generated from the unmanaged code.

If an exception is generated in unmanaged code, it is caught and translated to an appropriate managed exception and rethrown. The only exception would be when no appropriate managed exception exists to which to convert. You have already seen that throwing an unspecified exception such as the following

Throw;

results in an SEHException. In fact, any exception that is thrown that cannot be translated to its managed counterpart results in an SEHException.

A sample in the UnmanagedException directory raises four different exceptions from unmanaged code: divide-by-zero, null-reference, string, and a custom exception based on std::exception. The output of the sample looks like this:

Divide-by-zero

System.DivideByZeroException: Attempted to divide by zero.
   at UnmanagedException.NativeMethods.DivideByZero()
   at UnmanagedException.UnmanagedExceptionTest.Main(String[] args) in unmanagedexception
.cs:line 30

Memory Access

System.NullReferenceException: Value null was found where an instance of an object was
 required.
   at UnmanagedException.NativeMethods.MemoryAccess()
   at UnmanagedException.UnmanagedExceptionTest.Main(String[] args) in unmanagedexception
.cs:line 40

Fail

System.Runtime.InteropServices.SEHException: External component has thrown an exception.
   at UnmanagedException.NativeMethods.Fail()
   at UnmanagedException.UnmanagedExceptionTest.Main(String[] args) in unmanagedexception
.cs:line 50

Custom

System.Runtime.InteropServices.SEHException: External component has thrown an exception.
   at UnmanagedException.NativeMethods.Custom()
   at UnmanagedException.UnmanagedExceptionTest.Main(String[] args) in unmanagedexception
.cs:line 60

Notice that the first two types of exceptions can be translated directly to a managed counterpart. With the last two types of exceptions, a managed counterpart could not be found, so the default SEHException is thrown.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.137.161.222