The concept of an else
for a try
block doesn't exist in c++. It can be emulated with the use of a flag:
{
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();
}
}
The do_stuff_only_if_try_block_succeeded()
code is executed only if the try block executes without throwing an exception. Note that in the case that do_stuff_only_if_try_block_succeeded()
does throw an exception, that exception will not be caught. These two concepts mimic the intent of the python try ... catch ... else
concept.