为什么std :: exception在std :: bad_alloc之前捕获我的异常?

Eva*_*tis 13 c++ exception

问题:我使用std :: exception和std :: bad_alloc来捕获异常.我正在使用的try catch的顺序有问题.我附上了示例代码以供参考.

预期:如果我的错误是bad_alloc,则抛出bad_alloc异常.

观察:我的错误是bad_alloc,但抛出了异常.

示例代码:

#include "stdafx.h"
#include <iostream>
#include <exception>

using namespace std;

void goesWrong()
{
    bool error1Detected = true;
    bool error2Detected = false;

    if (error1Detected)
    {
        throw bad_alloc();
    }

    if (error2Detected)
    {
         throw exception();
    }
}

int main()
{
    try
    {
        goesWrong();
    }
    catch (exception &e)
    {
        cout << "Catching exception: " << e.what() << endl;
    } 
    catch (bad_alloc &e)
    {
        cout << "Catching bad_alloc: " << e.what() << endl;
    }

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

Bal*_*arq 23

关于它们的继承关系,您必须以相反的顺序放置异常.std :: exceptionstd :: bad_alloc的父类,这就是之前在catch列表中找到它的原因.所以你必须将你的代码转换为:

   try {
      goesWrong();
   }
   catch (bad_alloc &e)
   {
      cout << "Catching bad_alloc: " << e.what() << endl;
   }
   catch (exception &e)
   {
      cout << "Catching exception: " << e.what() << endl;
   }
Run Code Online (Sandbox Code Playgroud)

你不仅限于捕获对象:你可以抛出整数,字符......无论如何.在这种情况下,catch(...)是唯一可以捕获它们的安全方法.

也就是说,使用标准类库中的对象是建议的方法.在这种情况下,由于std :: exception是所有(标准)异常的基类,因此它将捕获所有可能抛出的异常.

您可以创建自己的异常类,从std :: exceptionstd :: runtime_error派生它们,例如,我个人的选择.

希望这可以帮助.