C++异常测试

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 1\n";;
    if( Ex.what() == What )
        cout << "OK 2\n";;
    if( Ex.what() == Out_of_range )
        cout << "OK 3\n";;
    if( Ex.what() == "stol argument out of range" )
        cout << "OK 4\n";;
}

结果是

OK 1
OK 2
OK 3

问题一:为什么第四条if语句为假?

问题 2:除了使用 what 成员之外,还有其他方法来测试异常吗?

Question 1: why is the fourth if statement false?

在那一行中,您比较的是两个 char const*,而不是两个字符串。

Question 2: is there another way to test an exception than using the what member?

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
}

"Question 1: why is the fourth if statement false?"

std::exception::what()的签名是

virtual const char* what() const;

字符串文字和 what() 的结果不太可能指向在您的情况下进行比较的相同内存地址。

"Question 2: is there another way to test an exception than using the what member?"

是的。使用多个 catch() {} 块,一个用于每个特定的异常类型。你也应该 catch() 例外 const 参考:

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
}