Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
204 views
in Technique[技术] by (71.8m points)

c++ - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

From the Standard, 15.1/8

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...