c++ - 停在 "Exception Unhandled"的类和 visual studio 2019 未捕捉到异常

标签 c++ exception

我正在尝试创建一个具有处理所有异常的方法的类。它接受指向函数的指针,执行该函数,然后在函数抛出异常时进行处理。然后我创建了一个函数获取一个无效的子字符串来证明异常被捕获,但是,我的类没有得到异常并且 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_rangenot派生自 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/

相关文章:

c++ - QT Quick 或 C++ 检查有效的电子邮件输入(电子邮件格式验证器)

c++ - 为什么不能存储基类的函数指针?

swift - “ fatal error :在展开可选值时意外发现nil”是什么意思?

java - 异常处理与手动检查条件

c++ - 在 OpenGL C++ 中旋转子对象

c++ - linux c++ xlib,如何使用 XSaveContext 和 XFindContext(提供示例)

python - 将类限制为最多一个实例时要抛出哪种 Python 异常?

c# - Visual Studio C++ 和 C# 的异常报告组件

c# - 在代码的生命周期内处理异常的最佳方法是什么?

c++ - 如何在 C++ 中正确转换结构