Boost C++ Libraries

...one of the most highly regarded and expertly designed C++ library projects in the world. Herb Sutter and Andrei Alexandrescu, C++ Coding Standards

This is the documentation for an old version of Boost. Click here to view this page for the latest version.
PrevUpHomeNext

BOOST_<level>_EXCEPTION

BOOST_WARN_EXCEPTION(expression, exception_type, predicate);
BOOST_CHECK_EXCEPTION(expression, exception_type, predicate);
BOOST_REQUIRE_EXCEPTION(expression, exception_type, predicate);

As for BOOST_<level>_THROW, these assertions validate that expression raises an exception of the type specified by exception_type or any of its child type, with additional checks on the exception instance.

predicate should be a unary function accepting an instance of exception_type or any of its child, and that should return a boolean indicating a success (true) or a failure (false).

[Warning] Warning

the assertion catches only the expected exceptions.

[Tip] Tip

It is possible to test for complex expressions with the use of constructs such as do { /* ... */} while(0) block.

The example below checks that the exception carries the proper error code.

Example: BOOST_<level>_EXCEPTION usage

Code

#define BOOST_TEST_MODULE example
#include <boost/test/included/unit_test.hpp>

struct my_exception
{
  explicit my_exception( int ec = 0 ) : m_error_code( ec )
  {}

  int m_error_code;
};

bool is_critical( my_exception const& ex ) { return ex.m_error_code < 0; }

void some_func( int i ) { if( i>=0 ) throw my_exception( i ); }

BOOST_AUTO_TEST_CASE( test_exception_predicate )
{
  BOOST_CHECK_EXCEPTION( some_func(0), my_exception, !is_critical );
  BOOST_CHECK_EXCEPTION( some_func(1), my_exception, is_critical );
}

Output

> example --log_level=success
Running 1 test case...
Entering test module "example"
test:24: Entering test case "test_exception_predicate"
test:26: info: check 'exception "my_exception" raised as expected: validation on the raised exception through predicate "!is_critical"' has passed
test:27: error: in "test_exception_predicate": exception "my_exception" raised as expected: validation on the raised exception through predicate "is_critical"
test:24: Leaving test case "test_exception_predicate"; testing time: 203us
Leaving test module "example"; testing time: 271us

*** 1 failure is detected in the test module "example"

See also:


PrevUpHomeNext