gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 21:42:02 26 4
gpt4 key购买 nike

问题:我同时使用 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;
}

最佳答案

关于它们的继承关系,您必须以相反的顺序放置您的异常。 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;
}

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

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

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

希望这会有所帮助。

关于c++ - 为什么 std::exception 在 std::bad_alloc 之前捕获我的异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48619669/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com