我想知道是否有一个else语句,比如在python中,当附加到 try-catch 结构时,如果没有抛出异常,则使其中的代码块只能执行/捕获。
例如:
try {
//code here
} catch(...) {
//exception handling here
} ELSE {
//this should execute only if no exceptions occurred
}
答案 0 :(得分:8)
为什么不把它放在try块的末尾?
答案 1 :(得分:2)
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();
}
}
仅在try块执行而不会引发异常的情况下执行do_stuff_only_if_try_block_succeeded()
代码。请注意,在do_stuff_only_if_try_block_succeeded()
确实引发异常的情况下,将不会捕获该异常。这两个概念模仿了python try ... catch ... else
概念的意图。