gpt4 book ai didi

c++ - 使用 RAII 嵌套异常

转载 作者:IT老高 更新时间:2023-10-28 23:20:35 25 4
gpt4 key购买 nike

所以在 C++ 中使用 std::nested_exception 嵌套异常的方法是:

void foo() {
try {
// code that might throw
std::ifstream file("nonexistent.file");
file.exceptions(std::ios_base::failbit);
}

catch(...) {
std::throw_with_nested(std::runtime_error("foo failed"));
}
}

但是这种技术在希望嵌套异常的每一层都使用显式的 try/catch block ,这至少可以说是丑陋的。

RAII,Jon Kalb expands作为“责任获取就是初始化”,是一种处理异常的更简洁的方法,而不是使用显式的 try/catch block 。使用 RAII,显式 try/catch block 主要仅用于最终处理异常,例如为了向用户显示错误消息。

查看上面的代码,在我看来,输入 foo() 可以被视为有责任将任何异常报告为 std::runtime_error("foo failed") 并将详细信息嵌套在 nested_exception 中。如果我们可以使用 RAII 来承担这个责任,那么代码看起来会更干净:

void foo() {
Throw_with_nested on_error("foo failed");

// code that might throw
std::ifstream file("nonexistent.file");
file.exceptions(std::ios_base::failbit);
}

这里有没有办法使用 RAII 语法来替换显式的 try/catch block ?


为此,我们需要一个类型,当调用其析构函数时,检查析构函数调用是否是由于异常,如果是则嵌套该异常,并抛出新的嵌套异常,以便正常展开。这可能看起来像:

struct Throw_with_nested {
const char *msg;

Throw_with_nested(const char *error_message) : msg(error_message) {}

~Throw_with_nested() {
if (std::uncaught_exception()) {
std::throw_with_nested(std::runtime_error(msg));
}
}
};

然而,std::throw_with_nested() 要求“当前处理的异常”处于事件状态,这意味着它只能在 catch block 的上下文中工作。所以我们需要这样的东西:

  ~Throw_with_nested() {
if (std::uncaught_exception()) {
try {
rethrow_uncaught_exception();
}
catch(...) {
std::throw_with_nested(std::runtime_error(msg));
}
}
}

不幸的是,据我所知,没有像 C++ 中定义的 rethrow_uncaught_excpetion() 这样的东西。

最佳答案

如果没有在析构函数中捕获(并消耗)未捕获异常的方法,则无法在没有 std::terminate< 的析构函数上下文中重新抛出异常,无论是否嵌套 被调用(当在异常处理的上下文中抛出异常时)。

std::current_exception(结合 std::rethrow_exception)只会返回一个指向当前处理的异常的指针。这排除了它在这种情况下的使用,因为这种情况下的异常是明确未处理的。

鉴于上述情况,唯一给出的答案是从美学的角度来看。函数级别的 try block 使它看起来不那么难看。 (根据您的风格偏好进行调整):

void foo() try {
// code that might throw
std::ifstream file("nonexistent.file");
file.exceptions(std::ios_base::failbit);
}
catch(...) {
std::throw_with_nested(std::runtime_error("foo failed"));
}

关于c++ - 使用 RAII 嵌套异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20036138/

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