异常处理中的C++ Else语句

J3S*_*TER 6 c++ exception-handling flow-control

我想知道是否有一个else语句,比如在python中,当附加到try-catch结构时,如果没有抛出/捕获异常,则使其中的代码块只能执行.

例如:

try {
    //code here
} catch(...) {
    //exception handling here
} ELSE {
    //this should execute only if no exceptions occurred
}
Run Code Online (Sandbox Code Playgroud)

Dav*_*men 8

c++ 中不存在elsefortry块的概念。可以使用标志来模拟它:

{
    bool exception_caught = true;
    try
    {
        // Try block, without the else code:
        do_stuff_that_might_throw_an_exception();
        exception_caught = false; // This needs to be the last statement in the try block
    }
    catch (Exception& a)
    {
        // Handle the exception or rethrow, but do not touch exception_caught.
    }
    // Other catches elided.

    if (! exception_caught)
    {
        // The equivalent of the python else block goes here.
        do_stuff_only_if_try_block_succeeded();

    }
}
Run Code Online (Sandbox Code Playgroud)

do_stuff_only_if_try_block_succeeded()代码被执行只有在try块的执行没有抛出异常。请注意,如果 do_stuff_only_if_try_block_succeeded()确实抛出异常,则不会捕获该异常。这两个概念模仿了 pythontry ... catch ... else概念的意图。


Chr*_* S. 7

为什么不把它放在try块的末尾?

  • Python [document](https://docs.python.org/2.7/tutorial/errors.html)说,"它避免意外捕获由`try ...保护的代码引发的异常. "声明." 我不判断它是否好,这正是消息来源所说的. (6认同)
  • @ J3STER对此表示不同意。处理“其他”情况将使只有单一的代码流(除非确实发生了例外)被完全忽略的观点破灭了这一点。如果没有抛出异常,则try块中的所有内容均为“ else”。 (2认同)
  • @ J3STER:为什么这会使代码变得更好?!现有的异常机制已经可以让你完全按照自己的意愿行事*而无需任何额外的结构*. (2认同)
  • 因为您将放在 else 中的代码块可能会导致您不想捕获的异常 (2认同)