C++中是否定义好了?我被迫'异常'转换为返回代码(许多C用户使用该API,因此我需要确保在控制返回给调用者之前处理所有C++异常都被捕获&)。在嵌套的'try'中重新抛出合法的异常吗?
enum ErrorCode {…};
ErrorCode dispatcher() {
try {
throw;
}
catch (std::bad_alloc&) {
return ErrorCode_OutOfMemory;
}
catch (std::logic_error&) {
return ErrorCode_LogicError;
}
catch (myownstdexcderivedclass&) {
return ErrorCode_42;
}
catch(...) {
return ErrorCode_UnknownWeWillAllDie;
}
}
ErrorCode apifunc() {
try {
// foo() might throw anything
foo();
}
catch(...) {
// dispatcher rethrows the exception and does fine-grained handling
return dispatcher();
}
return ErrorCode_Fine;
}
ErrorCode apifunc2() {
try {
// bar() might throw anything
bar();
}
catch(...) {
return dispatcher();
}
return ErrorCode_Fine;
}
我希望样本能显示我的意图。我的猜测是这是未定义的行为,但我不确定。如果适用,请提供标准报价。备选方法也受到赞赏。
谢谢!
我记得考虑采用这种方法来减少来自不同try/catch块的代码重复,但我实现了它。是什么让你认为这可能是非法的? – 2010-03-17 21:50:55
我也曾使用过这个技巧 – iain 2010-03-17 22:26:25
@jdv - 我感觉有点不舒服,从嵌套在catch-clause(甚至在不同的堆栈框架)中的try块中重新抛出。它看起来有点太漂亮了,所以我想保持安全。 – 2010-03-17 22:34:02