Visual Studio 2013 - C++ 异常测试

visual studio 2013 - C++ Exception testing

本文关键字:异常 测试 C++ Studio 2013 Visual      更新时间:2023-10-16

我想测试返回了什么异常。在异常处理的所有示例中,我看到它们只是打印一些消息,没有对异常类型进行真正的测试。所以我试了这个:

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::strtolstd::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
}