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)
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概念的意图。
为什么不把它放在try块的末尾?
| 归档时间: |
|
| 查看次数: |
3674 次 |
| 最近记录: |