C ++ Try-Catch语句未捕获异常

Jon*_*Jon 2 c++ try-catch c++17

我正在用C ++编写一个非常简单的单元测试框架,该框架使用try-catch语句来分析变量。在此示例中,我的类的标题UnitTest为一个公共,一个私有成员函数的标题为scalars_are_equal()is_equal()。用户必须传递str给公共功能,该功能包含带有测试名称的字符串。用户还必须传递value1并传递value2到包含两个要相互比较的标量值的公共函数。公共职能使用try语句并将数据传递到私有函数,在私有函数中对这两个变量进行求值以查看它们是否匹配。如果值匹配,则返回到调用函数,在该函数中将消息打印到屏幕上,以使用户知道测试已通过。如果值不相等,则私有函数应引发分配给字符串的异常msg,而公共函数应捕获此异常。该课程附在下面。这些函数被编写为模板函数,因此即使浮点算术可能意味着数字的两个版本并不完全相同,用户也可以选择比较整数,浮点数和双精度数。

class UnitTest
{
public:
    template <class type1, class type2>
    void scalars_are_equal(std::string str, const type1 &value1, const type2 &value2);
private:
    template <class type1, class type2>
    void is_equal(const type1 &value1, const type2 &value2, std::string str);
};
// ================================================================
// ================================================================
// UnitTest PUBLIC member functions
template <class type1, class type2>
void UnitTest::scalars_are_equal(std::string str, const type1 &value1,
                             const type2 &value2)

{
    unsigned long remain;
    remain = 60 - str.length();
    try {
        is_equal(value1, value2, str);
        std::cout << str + std::string(remain, '.') +
        std::string("PASSED") << std::endl;
    }
    catch (const char* msg) {
        std::cout << msg << std::endl;
    }
}
// ----------------------------------------------------------------

template <class type1, class type2>
void UnitTest::is_equal(const type1 &value1, const type2 &value2,
                        std::string str)
{
    if (value1 != value2) {
        unsigned long remain;
        remain = 60 - str.length();
        std::string msg = str + std::string(remain, '.') + " FAILED";
        throw msg;
    }
Run Code Online (Sandbox Code Playgroud)

}

在这种情况下,主程序看起来像;

#include <iostream>
#include <string>
#include <vector>
#include <array>

#include "unit_test.hpp"

int main(int argc, const char * argv[]) {
    UnitTest q;
{    // Test to see if code catches unequal scalars
    float a, b;
    a = 20.0;
    b = 30.0;
    std::string c ("Scalars_Unequal_Test");
    q.scalars_are_equal(c, a, b);
}
Run Code Online (Sandbox Code Playgroud)

由于我不明白的原因,catch该函数中的语句scalars_are_equal()未捕获该is_equal()函数。起初我以为是因为该函数引发了std::string,但是当我将catch语句从const char更改为std :: string时,它没有任何区别。有谁知道为什么这没有捕捉到异常?

use*_*709 8

您在UnitTest :: is_equal()中抛出了std :: string而不是char *。

std::string msg = str + std::string(remain, '.') + " FAILED";
throw msg;
Run Code Online (Sandbox Code Playgroud)

因此,您必须捕获一个字符串:

catch (std::string& msg) {
    std::cout << msg << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

重要的注意事项:不要抛出std :: string或类似的东西,而是从std :: exception或您自己的异常基类派生的类。例如:

 std::string msg = str + std::string(remain, '.') + " FAILED";
 throw std::runtime_error(msg);
 [...]
 catch (std::runtime_error& e) {
    std::cout << e.what() << std::endl;
 }
Run Code Online (Sandbox Code Playgroud)