ASSERT_THROW认为我的异常属于另一种类型
ASSERT_THROW thinks my exception is of a different type
在Google测试中,当我运行以下测试时:
void ThrowInvalidArgument()
{
throw new std::invalid_argument("I am thrown an invalid_argument");
}
TEST(ExpectExceptions, Negative)
{
ASSERT_THROW(ThrowInvalidArgument(), std::invalid_argument);
}
我得到以下失败:
error: Expected: ThrowInvalidArgument() throws an exception
of type std::invalid_argument.
Actual: it throws a different type.
[ FAILED ] ExpectExceptions.Negative (1 ms)
我做错了什么?
您正在抛出std::invalid_argument*
类型的实例,即指针。
投掷一个物体:
void ThrowInvalidArgument()
{
throw std::invalid_argument("I am thrown an invalid_argument");
// ^ (no new)
}
扩展Pjoter的有效答案:异常总是应该从普通的临时实例中抛出,并作为常量引用捕获:
void ThrowInvalidArgument() {
throw std::invalid_argument("I am thrown an invalid_argument");
}
void Elsewhere {
try {
}
catch(const std::invalid_argument& invalidArgEx) {
}
}
相关文章:
- 处理多个异常集合的C++方法
- 我在c++代码中生成了一个运行时#3异常
- 孤立代码块在结构中引发异常
- C++中的赋值发生,尽管右侧出现异常
- 从构造函数抛出异常时如何克服内存泄漏
- 异常属于C++中的线程还是进程
- 当类定义不可见时捕获异常
- 为什么我不能将一个对象push_back到属于另一个类的对象向量中?
- 引发异常:读取访问冲突**dynamicArray**为0x1118235.发生
- 为什么异常不退出程序?
- 为什么我应该在异常处理中使用std::cerr而不是std::cout
- 如何修复链表类实现的未处理异常0xDDDDDDDD
- 关于:C++中异常对象的范围:为什么我没有得到副本?
- 如果我已经有一个头,那么模板(-t)文件属于哪里
- 是什么导致了Unity 3D中的"错误线程异常"?
- 如何将strftime中的格式错误作为异常捕获
- 创建具有 new in 函数和"this is nullptr"异常的对象
- 尝试使用智能指针时引发异常
- 函数如何通知用户它基于函数原型抛出异常?
- ASSERT_THROW认为我的异常属于另一种类型