异常未捕获在try catch块中 [英] Exception not caught in try catch block

查看:129
本文介绍了异常未捕获在try catch块中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I do a simple throw "TEST THROW" and it isn't caught in my catch (std::exception& e). Is it because I'm catching an std::exception& e? I mean, are only exception classes derived from std::exception caught? If not, am I doing something wrong or is it normal? By the way, none of the two catch blocks caught the throw exception.

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;

}

推荐答案

您正在抛出 const char * std :: exception 仅捕获 std :: exception 及其所有派生类。因此,为了赶上您的投掷,您应该投掷 std :: runtime_error( TEST THROW)。或 std :: logic_error( TEST THROW);任何合适的选择。 std :: exception 的派生类为在这里列出

You're throwing a const char*. std::exception only catches std::exception and all derived classes of it. So in order to catch your throw, you should throw std::runtime_error("TEST THROW") instead. Or std::logic_error("TEST THROW"); whatever fits better. The derived classes of std::exception are listed here.

这篇关于异常未捕获在try catch块中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆