Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens if a throw; statement is executed outside of catch block?

In C++ throw; when executed inside a catch block rethrows the currently caught exception outside the block.

In this answer an idea of exception dispatcher is brought up as a solution to reducing code duplication when using complex exception handling often:

try {
    CodeThatMightThrow();
} catch(...) {
    ExceptionHandler();
}

void ExceptionHandler()
{
    try {
        throw;
    } catch( FileException* e ) {
        //do handling with some complex logic
        delete e;
    } catch( GenericException* e ) {
        //do handling with other complex logic
        delete e;
    }
}

Throwing a pointer or a value doesn't make any difference so it's out of the question.

What happens if ExceptionHandler() is called not from a catch block?

I tried this code with VC7:

int main( int, char** )
{   
    try {
        throw;
    } catch( ... ) {
        MessageBox( 0, "", "", 0 );
    }
    return 0;
 }

First it causes the debugger to indicate a first-chance exception, then immediately an unhandled exception. If I run this code outside the debugger the program crashes the same way as if abort() has been called.

What is the expected behaviour for such situations?

like image 271
sharptooth Avatar asked Jun 11 '09 14:06

sharptooth


People also ask

What happens if an exception is thrown outside a catch block?

If a catch block ends normally, without a throw , the flow of control passes over all other catch blocks associated with the try block. Whenever an exception is thrown and caught, and control is returned outside of the function that threw the exception, stack unwinding takes place.

Can Throw be used outside try block?

3. throw: The throw keyword is used to transfer control from the try block to the catch block. 4. throws: The throws keyword is used for exception handling without try & catch block.

What happens when you throw an error in a catch block?

One related and confusing thing to know is that in a try-[catch]-finally structure, a finally block may throw an exception and if so, any exception thrown by the try or catch block is lost.

Will statements execute after catch block?

Statements after the catch block still got executed after an exception occured.


1 Answers

From the Standard, 15.1/8

If no exception is presently being handled, executing a throw-expression with no operand calls std::terminate().

like image 153
James Hopkin Avatar answered Nov 06 '22 02:11

James Hopkin