PortMan
PortMan

Reputation: 4523

ASSERT_THROW thinks my exception is of a different type

In Google Test, when I run the following test:

void ThrowInvalidArgument()
{
   throw new std::invalid_argument("I am thrown an invalid_argument");
}

TEST(ExpectExceptions, Negative)
{
  ASSERT_THROW(ThrowInvalidArgument(), std::invalid_argument);
}

I get the following failure:

error: Expected: ThrowInvalidArgument() throws an exception
                 of type std::invalid_argument.
       Actual: it throws a different type.
[  FAILED  ] ExpectExceptions.Negative (1 ms)

What am I doing wrong?

Upvotes: 4

Views: 5324

Answers (2)

Piotr Skotnicki
Piotr Skotnicki

Reputation: 48447

You are throwing an instance of the std::invalid_argument* type, that is, a pointer.

Throw an object instead:

void ThrowInvalidArgument()
{
     throw std::invalid_argument("I am thrown an invalid_argument");
     //   ^ (no new)
}

Upvotes: 11

πάντα ῥεῖ
πάντα ῥεῖ

Reputation: 1

To extend on Pjotr's valid answer: Exceptions always should be thrown from plain temporary instances and caught as const references:

void ThrowInvalidArgument() {
    throw std::invalid_argument("I am thrown an invalid_argument");
}

void Elsewhere {
    try {
    }
    catch(const std::invalid_argument& invalidArgEx) {
    }
}

Upvotes: 3

Related Questions