Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Else statement in Exception Handling

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
}
like image 511
J3STER Avatar asked Jan 25 '17 01:01

J3STER


People also ask

What is use of else in exception handling?

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")

What is else statement in C?

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.

What is else in TRY except?

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.

Why is my else statement not working in C?

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".


2 Answers

Why not just put it at the end of the try block?

like image 160
Christoph S. Avatar answered Oct 06 '22 20:10

Christoph S.


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.

like image 11
David Hammen Avatar answered Oct 06 '22 22:10

David Hammen