是否有一种模式可以依次执行多个投掷函数?
Is there a pattern for executing multiple throwing functions after each other?
如果我想在一段代码中忽略异常,我正在寻找一种编写异常代码的好方法。
考虑
bool ClearAllCaches() {
bool success = ClearPersistentCache();
success &= ClearTransientCache();
success &= ClearRemoteCache();
return success;
}
如果这些函数抛出错误而不是返回成功值,并且我还想重新抛出这些函数之一抛出的任何异常,但只有在完成所有操作之后,是否有比这更干净的解决方案?
void ClearAllCaches() {
MyException persistentException = MyException(ErrorCode::None);
try {
ClearPersistentCache();
} catch (const MyException& e) {
persistentException = e;
}
//...same for ClearTransientCache()
ClearRemoteCache(); // <- does not have to be caught.
if (persistentException.getCode() != ErrorCode::None) {
throw persistentException;
}
//...same for ClearTransientCache()
}
是否可以以可读且不过于丑陋的方式编写此代码?
使用 lambda 和 std::exception_ptr
:
void ClearAllCaches() {
std::exception_ptr eptr;
auto CallAndStoreException = [&](auto func) {
try {
func();
} catch (...) {
eptr = std::current_exception();
}
};
CallAndStoreException(&ClearPersistentCache);
CallAndStoreException(&ClearTransientCache);
CallAndStoreException(&ClearRemoteCache);
if (eptr) {
std::rethrow_exception(eptr);
}
}
但是如果你丢掉先抛出的那些信息,你确定异常是正确的方式吗?如果您确定必须走这条路,也许还可以看看 std::nested_exception
如果我想在一段代码中忽略异常,我正在寻找一种编写异常代码的好方法。
考虑
bool ClearAllCaches() {
bool success = ClearPersistentCache();
success &= ClearTransientCache();
success &= ClearRemoteCache();
return success;
}
如果这些函数抛出错误而不是返回成功值,并且我还想重新抛出这些函数之一抛出的任何异常,但只有在完成所有操作之后,是否有比这更干净的解决方案?
void ClearAllCaches() {
MyException persistentException = MyException(ErrorCode::None);
try {
ClearPersistentCache();
} catch (const MyException& e) {
persistentException = e;
}
//...same for ClearTransientCache()
ClearRemoteCache(); // <- does not have to be caught.
if (persistentException.getCode() != ErrorCode::None) {
throw persistentException;
}
//...same for ClearTransientCache()
}
是否可以以可读且不过于丑陋的方式编写此代码?
使用 lambda 和 std::exception_ptr
:
void ClearAllCaches() {
std::exception_ptr eptr;
auto CallAndStoreException = [&](auto func) {
try {
func();
} catch (...) {
eptr = std::current_exception();
}
};
CallAndStoreException(&ClearPersistentCache);
CallAndStoreException(&ClearTransientCache);
CallAndStoreException(&ClearRemoteCache);
if (eptr) {
std::rethrow_exception(eptr);
}
}
但是如果你丢掉先抛出的那些信息,你确定异常是正确的方式吗?如果您确定必须走这条路,也许还可以看看 std::nested_exception