在try catch块中未捕获异常

Exception not caught in try catch block

本文关键字:捕获异常 try catch      更新时间:2023-10-16

我做了一个简单的抛出"TEST throw ",它不会在我的catch (std::exception&e) 。是因为我正在捕捉一个std::exception&吗?我的意思是,只有从std::exception派生的异常类被捕获吗?如果不是,是我做错了还是正常?顺便说一下,两个catch块都没有捕获抛出异常。

int main()
{
try
{
    throw "TEST THROW"; // TEST
    Core core;
    core.Init();
    core.Load();
    while (!core.requestCloseWindow)
    {
        core.HandleInput();
        core.Update();
        core.Draw();
    }
    core.Unload();
    core.window->close();
}
catch (std::exception& e)
{
    std::cerr << e.what() << std::endl;
    try
    {
        time_t rawTime;
        struct tm* timeInfo;
        char timeBuffer [80];
        time(&rawTime);
        timeInfo = localtime(&rawTime);
        strftime(timeBuffer, 80, "%F %T", timeInfo);
        puts(timeBuffer);
        std::ofstream ofs; // Pas besoin de close, car le destructeur le fait.
        ofs.exceptions(std::ofstream::failbit | std::ofstream::badbit);
        ofs.open("log.txt", std::ofstream::out | std::ofstream::app);
        ofs << e.what() << std::endl;
    }
    catch (std::exception& e)
    {
        std::cerr << "An error occured while writing to a log file!" << std::endl;
    }
}
return 0;

}

人们可能遇到这个问题的另一个原因,特别是如果他们最近一直在编写Java,是他们可能抛出一个指向异常的指针。

/* WARNING WARNING THIS CODE IS WRONG DO NOT COPY */
try {
    throw new std::runtime_error("catch me");
} catch (std::runtime_error &err) {
    std::cerr << "exception caught and ignored: " << err.what() << std::end;
}
/* WARNING WARNING THIS CODE IS WRONG DO NOT COPY */

不能接住你扔的std::runtime_error*。它可能会在调用std::terminate以获取未捕获的异常时死亡。

不要用new分配异常,只需按值抛出构造函数,例如

try {
    /* note: no 'new' here */
    throw std::runtime_error("catch me");
} catch (std::runtime_error &err) {
    std::cerr << "exception caught and ignored: " << err.what() << std::end;
}

你在扔一个const char*std::exception只捕获std::exception及其所有派生类。所以为了接住你的投掷,你应该投掷std::runtime_error("TEST THROW")代替。或std::logic_error("TEST THROW");随便什么更合适。下面列出了std::exception的派生类

可以添加抓住(…)

当你抛出一个继承类型的异常,但是继承是私有的

由于这不是MCVE (Core是什么?),我不能明确地解决这个问题,但您肯定错过了

#include <exception>

实际上,即使没有包含,GCC也会编译,但是异常不会被捕获,您将以

结束。

抛出'std::exception'实例后终止调用

(): std::异常

。/{program}: {PID} Aborted (core dump)