Quick Links:

bal | bbl | bdl | bsl

Namespaces

Component bsls_bslexceptionutil
[Package bsls]

Provide functions for use in bsl that throw standard exceptions. More...

Namespaces

namespace  bsls

Detailed Description

Outline
Purpose:
Provide functions for use in bsl that throw standard exceptions.
Classes:
bsls::BslExceptionUtil namespace for utilities to throw exceptions
See also:
bsl_exception, bsl_new, bsl_typeinfo
Description:
This component provides a means to throw standard exceptions without introducing a compile-time dependency on the standard exception classes. This is valuable where header files define function templates or inline functions that may throw these types as exceptions.
Usage:
This section illustrates intended use of this component.
Example 1: Throwing a standard exception:
Suppose we are implementing a class that must conform to the requirements of the C++ Standard. There are several clauses that dictate throwing an exception of a standard type to indicate failure. However, we do not want to expose the standard exception header to our clients, which would be typical when implementing function templates inline, and we want to have a consistent behavior when building with a compiler in a non-standard mode that does not support exceptions.
First we declare a function template that wants to throw a standard exception. Note that the exception header is not included at this point.
  #include <bsls_bslexceptionutil.h>

  template<typename T>
  void testFunction(int selector)
      //  Throw a standard exception according to the specified 'selector'.
  {
    switch (selector) {
Now we can use the utilities in this component to throw the desired exception, even though the standard exception classes are not visible to this code. Finally, we can write some client code that calls our function, and wishes to catch the thrown exception. Observe that this file must #include the corresponding standard header in order to catch the exception.
  #include <exception>
  #include <new>
  #include <typeinfo>

  void callTestFunction()
  {
      try {
          testFunction<int>(1);
          assert(0 == "Should throw before reaching here.");
      }
      catch (const std::bad_alloc& ex) {
      }

      try {
          testFunction<double>(2);
          assert(0 == "Should throw before reaching here.");
      }
      catch (const std::bad_cast& ex) {
      }
  }