Visual Studio 2013 - C++ 异常测试
visual studio 2013 - C++ Exception testing
我想测试返回了什么异常。在异常处理的所有示例中,我看到它们只是打印一些消息,没有对异常类型进行真正的测试。所以我试了这个:
string Out_of_range{ "stol argument out of range" };
long Long;
try{
Long = stol( "12345678901234567890" );
} catch( exception& Ex ){
string What = Ex.what();
if( What == Out_of_range )
cout << "OK 1n";;
if( Ex.what() == What )
cout << "OK 2n";;
if( Ex.what() == Out_of_range )
cout << "OK 3n";;
if( Ex.what() == "stol argument out of range" )
cout << "OK 4n";;
}
结果是
OK 1
OK 2
OK 3
问题1:为什么第四个if语句是假的?
问题 2:除了使用 what 成员之外,还有其他方法可以测试异常吗?
"问题1:为什么第四个if语句是假的?">
std::exception::what()
的签名是
virtual const char* what() const;
字符串文字和what()
的结果不太可能指向在您的情况下进行比较的相同内存地址。
"问题 2:除了使用 what 成员之外,还有没有其他方法来测试异常?">
是的。使用多个catch() {}
块,每个特定异常类型一个。此外,您还应该通过const
引用catch()
异常:
try{
Long = stol( "12345678901234567890" );
} catch(const std::invalid_argument& Ex) {
// Handle invalid_argument exception
} catch(const std::out_of_range& Ex) {
// Handle out_of_range exception
} catch( ... )
// Handle unexpected exception
}
问题1:为什么第四个if语句是假的?
在这一行中,您比较的是两个char const*
,而不是两个字符串。
问题 2:除了使用 what 成员之外,还有其他方法可以测试异常吗?
std::stol
可以引发以下异常 (http://en.cppreference.com/w/cpp/string/basic_string/stol(:
-
std::invalid_argument
如果无法执行转换 -
std::out_of_range
转换后的值是否超出结果类型的范围,或者如果基础函数(std::strtol
或std::strtoll
(将errno
设置为ERANGE
。
您可以对这两种类型的异常使用显式catch
块。
try
{
Long = stol( "12345678901234567890" );
}
catch( std::invalid_argument const& Ex )
{
// Deal with the exception
}
catch( std::out_of_range const& Ex )
{
// Deal with the exception
}
catch( exception const& Ex )
{
// Deal with the exception
}
相关文章:
- 禁用自动捕获 Googletest 单元测试中的C++异常
- gmock / google-mock发出警告,并且通过模拟异常未通过测试
- 异常模块测试C++
- 错误 在测试.exe 0x76C9FD62时出现未经处理的异常:Microsoft C++异常:内存位置0x006FF8
- 无法在谷歌测试中检查异常类型
- 助推.测试崩溃,***异常:MSVC上的其他
- 获取谷歌测试异常抛出消息
- 测试opencv-wwarpAffine的异常值数量
- 与 2013 年相比:断点进入 CPPunittest 测试引发异常
- C++内存不足异常测试
- 我们应该在C++单元测试中测试src代码断言(NOT异常)吗
- 如何从谷歌测试中的异常中获取回溯信息
- 单元测试失败,异常代码为c0000005
- 使用向量运算的单元测试中出现未处理的C++异常
- 在vs 2010中运行c++的单元测试时出现异常
- 创建 <InIter>iterator_traits::value_type 在通过时会触发尊重吗?(异常测试)
- CppUTest单元测试框架多定义异常
- Visual Studio 2013 - C++ 异常测试
- 测试引发特定的异常类型,并且异常具有正确的属性
- CUTE单元测试无法识别引发的异常