I would like to know if there is an else statement, like in python, that when attached to a try-catch structure, makes the block of code within it only executable if no exceptions were thrown/caught.
For instance:
try {
//code here
} catch(...) {
//exception handling here
} ELSE {
//this should execute only if no exceptions occurred
}
You can use the else keyword to define a block of code to be executed if no errors were raised: Example. In this example, the try block does not generate any error: try: print("Hello") except: print("Something went wrong") else: print("Nothing went wrong")
C has the following conditional statements: Use if to specify a block of code to be executed, if a specified condition is true. Use else to specify a block of code to be executed, if the same condition is false. Use else if to specify a new condition to test, if the first condition is false.
The try block lets you test a block of code for errors. The except block lets you handle the error. The else block lets you execute code when there is no error.
If you are getting an error about the else it is because you've told the interpreter that the ; was the end of your if statement so when it finds the else a few lines later it starts complaining. A few examples of where not to put a semicolon: if (age < 18); if ( 9 > 10 ); if ("Yogi Bear". length < 3); if ("Jon".
Why not just put it at the end of the try block?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With