Enhanced SEHException Handling

The problem with SEHException

There is indeed a problem with SEHException handling.

Let’s see the definition of SEHException from the official online document.

The SEHException class handles SEH errors that are thrown from unmanaged code, but that have not been mapped to another .NET Framework exception. The SEHException class also corresponds to the HRESULT E_FAIL (0x80004005).

The .NET Framework often encounters unmanaged SEH exceptions that are automatically mapped to managed equivalents. There are two common unmanaged SEH exceptions:

  • STATUS_NO_MEMORY exceptions are automatically mapped to the OutOfMemoryException class.
  • STATUS_ACCESS_VIOLATION exceptions are automatically mapped as follows:
    • If legacyNullReferencePolicy is applied, all access violations are mapped to the NullReferenceException class.
    • If the address at which the read/write was attempted is not in JIT-compiled code, the exception is mapped to theAccessViolationException class.
    • If the address at which the read/write was attempted is in JIT-compiled code, but it is not in the OS Null partition area, the exception is mapped to the AccessViolationException class.
    • If there is no legacyNullReferencePolicy, and the address at which the read/write was attempted is in JIT-compiled code and in the OS Null partition area, the exception is mapped to the NullReferenceException class.

Any SEH exception that is not automatically mapped to a specific exception is mapped to the SEHException class by default.

What is the problem? Well, the problem is .NET does not tell what it is if it is not mapped to .NET exception. When a SEHException occurs, the message of the exception always reads “External component has thrown an exception”. It is not really useful and can not be used to determine what really happened.

Enhanced SEHException Handling

xInterop C++ .NET Bridge introduces a feature of parsing the current execution exception and creating a new type of EnhancedSEHException which is derived from SEHException. When calling a underlying native C++ method, it is always wrapped inside a try catch block so that an enhanced SEHException will be thrown when a SEHException is caught. An instance of EnhancedSEHException contains the real message passed from the native C++ DLL and the type of the object thrown.

If you open xInterop C++ .NET Bridge, you can find a demo project called Enhanced SEH Exception Handling as shown below.

Step 1:

image

Step 2: Choose the options to create Exception Handling Sample project.

image

Step 3: The C# .NET Exception Handling Sample Project has been created.

image

image

Testing

I am showing the complete testing application C# file below. You may want to take a look into the details yourself or trying the sample project using xInterop C++ .NET Bridge.

Running the application.

image

Translate »