[Previous] [Contents] [Next]

Chapter Six

Exceptions

Error handling is a contentious issue among developers. For a long time, most C programmers subscribed to the every-function-call-returns-an-error-code style of coding. While effective, this error-handling mechanism has its drawbacks. To start with, error-handling code is sprinkled throughout an application, which makes the code hard to read and costly to maintain. This approach can also be inefficient because it requires a great deal of usually unnecessary code that simply checks for error return codes.

More recently, languages such as C++ and Java have introduced an error-handling mechanism known as exceptions. Exceptions are run-time errors by another name. Programming languages that support exceptions have special language directives that allow exceptions to be caught and raised. Raising an exception is a way to report an error; catching an exception means intercepting and responding to the error condition. C++ and Java support the try and catch keywords for trapping exceptions, while the throw keyword is used to raise exceptions. Even Microsoft Visual Basic supports trapping exceptions with the On Error statement; you use the Err.Raise method to raise exceptions.

To the designers of COM+, error handling represented a unique challenge because each programming language has its own ideas about error handling. As a language-neutral component architecture, COM+ must deal with errors in a way that is compatible with all major programming languages, some of which might not support exceptions. To meet that goal, COM+ supports both the errors-as-return-codes technique and the more modern idea of exceptions.

For method return codes, COM+ defines the HRESULT, a 32-bit value that identifies an error. In the exception-handling arena, COM+ defines several interfaces that support those semantics. Some high-level languages such as Visual Basic automatically map COM+ exceptions to the language's native exception-handling mechanism. In lower-level languages such as C++, COM+ exceptions are not automatically mapped to the C++ exception-handing mechanism. Instead, C++ developers must work directly with the COM+ exception interfaces or roll their own mapping layer that converts COM+ exceptions to C++ exceptions and vice versa. The Microsoft Java Virtual Machine (VM) also provides nearly automatic COM+ to Java exception translation. The error-handling technique you employ will depend on the programming language you use and your preferences about how to deal with errors.