中重新抛出异常是否合法

中重新抛出异常是否合法

本文介绍了在嵌套的“try”中重新抛出异常是否合法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 以下是在C ++中定义的,还是不是?我被迫转换异常到返回代码(有问题的API被许多C用户使用,所以我需要确保所有C ++异常在控制被返回到调用者之前捕获和处理)。 枚举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()可能抛出任何东西 foo } catch(...){ // dispatcher重新抛出异常并进行细粒度处理 return dispatcher(); } return ErrorCode_Fine; } ErrorCode apifunc2(){ try { // bar()可能抛出任何东西 bar(); } catch(...){ return dispatcher(); } return ErrorCode_Fine; } 我希望示例显示我的意图。我的猜测是,这是未定义的行为,但我不知道。请提供标准报价(如适用)。 谢谢!解决方案精细。异常被激活,直到它被捕获,它变得不活动。 从标准中,强调我的:这是 catch(...) {//< - / * ... * / } // 那些箭头,你可以重新抛出异常。 请记住,如果调用 dispatch 时没有活动异常, terminate 将被调用。如果 dispatch 在处理程序中抛出异常,则异常将开始传播。有关相关问题的详细信息。 / p> Is the following well-defined in C++, or not? I am forced to 'convert' exceptions to return codes (the API in question is used by many C users, so I need to make sure all C++ exceptions are caught & handled before control is returned to the caller).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;}I hope the sample shows my intention. My guess is that this is undefined behaviour, but I'm not sure. Please provide quotes from the standard, if applicable. Alternative approaches are appreciated as well.Thanks! 解决方案 That's fine. The exception is active until it's caught, where it becomes inactive. But it lives until the scope of the handler ends. From the standard, emphasis mine:That is:catch(...){ // <-- /* ... */} // <--Between those arrows, you can re-throw the exception. Only when the handlers scope ends does the exception cease to exist.Keep in mind if you call dispatch without an active exception, terminate will be called. If dispatch throws an exception in one if it's handlers, that exception will begin to propagate. More information in a related question. 这篇关于在嵌套的“try”中重新抛出异常是否合法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
08-19 23:01