1

I'm basically lost on this one. I've looked at Boost doc plus searching on SO, but I don't seem to find a thing. Assuming a class modelling Fraction, I want to throw an exception when divider is to be set to 0.

void Fraction::setQ(int q) {
    if (q == 0){
        throw new std::logic_error("Divider must not be null");
    }else{
         q_ = q;
    }
}

And this code is tested with this block of code

BOOST_AUTO_TEST_CASE( NonZeroDivider ){
    BOOST_CHECK_THROW(
        f->setQ(0),
        std::logic_error
    );
}

But when boost should catch the exception, it doesn't and prints an error followed by a failure

unknown location(0): fatal error in "NonZeroDivider": unknown type

If you could help me on this one, I've tried BOOST_CHECK_EXCEPTION (with necessary editions) but no idea. Always the same behavior. Thanks!

1 Answers1

2

Your code doesn't throw an exception (std::logic_error), it throws a pointer to a dynamically allocated exception (std::logic_error*); see throw new std::exception vs throw std::exception.

The fix is to remove the new keyword:

throw new std::logic_error("Divider must not be null");
      ~~~~
Community
  • 1
  • 1
ecatmur
  • 152,476
  • 27
  • 293
  • 366