Mapping C Exceptions to Managed Exceptions

In addition to exception-safe resource management, managed wrapper libraries must also care about mapping C++ exceptions thrown by the native library to managed exceptions. For example, let's assume that the SampleCipher algorithm supports only 128-bit and 256-bit key sizes. The constructor of NativeLib::SampleCipher could throw a NativeLib::CipherException when a key of the wrong size is passed. As discussed in Chapter 9, C++ exceptions are mapped to System::Runtime::InteropServices::SEHExceptions, which are not useful for the user of a wrapper library. Therefore it is necessary to catch native exceptions and rethrow managed exceptions with equivalent information.

To map exceptions in constructors, the function-try block can be used as shown in the following code. As discussed in Chapter 6, this allows you to catch exceptions thrown during member initialization as well as exceptions thrown in the constructor's body.

SampleCipher::SampleCipher(array<Byte>A key) try

: pKey(o), pWrappedObject(o)

..// same implementation as before }

catch(NativeLib::CipherException& ex) {

throw gcnew CipherException(gcnew String(ex.what()));

Even though no exceptions are expected from the member initialization list in the preceding code, it uses a function-try block. This ensures that exceptions are caught when you extend the member initialization by adding a member variable to the class or by deriving SampleCipher from another class.

Was this article helpful?

0 0

Post a comment