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

C++ Else statement in Exception Handling

我想知道是否有 else 语句,如 python,当附加到 try-catch 结构时,使代码块如果没有例外 thrown/caught.

,则只能在其中执行

例如:

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

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

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

{
    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();

    }
}

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