C++ Assertion function to check that Exception is thrown

user2054936 picture user2054936 · Mar 27, 2013 · Viewed 7.6k times · Source

I'm familiar with how the standard C++ assertion works. This has worked well in my project for a variety of testing purposes.

For example, suppose that I want to check that a certain exception is thrown by my code.

Is this possible to do without using a testing framework like CPPUnit?

Answer

jplatte picture jplatte · Mar 1, 2015

You can do the same thing CPPUnit does manually:

bool exceptionThrown = false;

try
{
    // your code
}
catch(ExceptionType&) // special exception type
{
    exceptionThrown = true;
}
catch(...) // or any exception at all
{
    exceptionThrown = true;
}

assert(exceptionThrown); // or whatever else you want to do

Of course, if you use this pattern a lot, it makes sense to use a macro for this.