我正在尝试创建一个具有处理所有异常的方法的类。它接受指向函数的指针,执行该函数,然后在函数抛出异常时进行处理。然后我创建了一个函数获取一个无效的子字符串来证明异常被捕获,但是,我的类没有得到异常并且 Visual Studio 在子字符串行上中断说“Exception Unhandled”
cpp文件:
#include "TestHarness.h"
using namespace TestHarness;
int testFunc();
int main()
{
Tester myTest;
std::cout << myTest.execute(testFunc);
return 0;
}
int testFunc()
{
std::cout << "My Test Func" << std::endl << std::endl;
std::string("abc").substr(10);
return 6;
}
h 文件:
#define TESTHARNESS_H
#include <vector>
#include <iostream>
#include <sstream>
#include <string>
namespace TestHarness
{
class Tester
{
public:
int execute(int(*func)());
private:
bool result;
};
int Tester::execute(int(*func)())
{
try {
(*func)();
result = true;
return 1;
}
catch (const std::runtime_error& e)
{
std::cout << e.what();
result = false;
return 0;
}
}
}
#endif
最佳答案
这很简单,真的:substr
抛出 std::out_of_range
,not派生自 std::runtime_error
但派生自 std::logic_error
,它本身派生自 std::exception
。只需捕获 std::exception const &
或 std::logic_error const &
。这是一个list of inheritance对于所有标准异常类型。
关于c++ - 停在 "Exception Unhandled"的类和 visual studio 2019 未捕捉到异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58489634/