如何解决co_await 之后当前处理的异常是什么?
GCC 允许从 catch
部分恢复 C++20 协程,并在协程中从其 co_await
部分再次调用 catch
。
在这种情况下,当前处理的异常被认为是什么?
请举个例子:
#include <coroutine>
#include <iostream>
struct ReturnObject {
struct promise_type {
ReturnObject get_return_object() { return { std::coroutine_handle<promise_type>::from_promise(*this) }; }
std::suspend_always initial_suspend() { return {}; }
std::suspend_always final_suspend() noexcept { return {}; }
void unhandled_exception() {}
void return_void() {}
};
std::coroutine_handle<promise_type> h_;
};
ReturnObject coroutine()
{
try {
std::cout << "Exception 1 being thrown\n";
throw 1;
}
catch( int a ) {
std::cout << "Exception caught in coroutine " << a << std::endl;
co_await std::suspend_always{};
try {
std::cout << "Current exception being rethrown\n";
throw;
}
catch( int b ) {
std::cout << "Exception caught in coroutine " << b << std::endl;
}
}
}
int main()
{
auto h = coroutine().h_;
try {
std::cout << "Exception 0 being thrown" << std::endl;
throw 0;
}
catch( int a ) {
std::cout << "Exception " << a << " caught in main" << std::endl;
h();
}
h();
h.destroy();
}
它打印(https://gcc.godbolt.org/z/4deoG7Pnh):
Exception 0 being thrown
Exception 0 caught in main
Exception 1 being thrown
Exception caught in coroutine 1
Current exception being rethrown
Exception caught in coroutine 0
这里我最感兴趣的是最后一行,因为它显示 throw;
重新抛出 0
而不是 1
,后者实际上是正在处理的。正确吗?
解决方法
var x = [6,4,3]; //pre-defined values
var n = 24; //the number I want to add too
function myFunc(values,goal) {
let result = [];
while (true) {
// Add random value
result.push(values[Math.floor(Math.random() * values.length)]);
// Calc sum
var sum = result.reduce((acc,val) => acc + val);
// If success,return
if (sum == goal) return result;
// If too large,start over
else if (sum > goal) result = [];
}
}
for (let i = 0; i < 10; i++) {
console.log(myFunc(x,n));
}
只能出现在 co_await
块之外,如 specified by the standard:
await 表达式只能出现在处理程序外部的函数体复合语句中的潜在求值表达式中。
catch
被定义为 co_yield
的变体,所以它有 the same limitations:
yield 表达式只能出现在函数 ([expr.await]) 的挂起上下文中。
因此编译器应该认为代码格式错误并发出错误。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。