tags:

views:

162

answers:

6

I have some technical questions. In this function:

string report() const {
    if(list.begin() == list.end()){
        throw "not good";
    }
    //do something
}

If I throw the exception what is going on with the program? Will my function terminate or will it run further? If it terminates, what value will it return?

+3  A: 

Your function will terminate immediately, and it won't return anything. If there are no catch statements catching the exception "up the call chain", your application will terminate.

Philippe Leybaert
+7  A: 

If you throw an exception, all functions will be exited back to the point where it finds a try...catch block with a matching catch type. If your function isn't called from within a try block, the program will exit with an unhandled exception.

Check out http://www.parashift.com/c++-faq-lite/exceptions.html for more info.

Cogwheel - Matthew Orlando
+4  A: 

It will basically go up the stack until it finds an exception handler; if it gets to the end of the stack without finding one, your program will crash. If it does find one, it will rewind the stack up that point, run the handler, and continue with the code after the handler block, however far up your stack that may be.

You can get all sorts of details about C++'s exception handling mechanism through Google. Here's a head start.

Adrian Petrescu
+1  A: 

It won't return, it will in fact terminate and reach the "nearest" (call-stack-wise) try...catch block. If none is found, most of the time the program just exits, on some platforms the error can be printed, I don't know the specifics of that though (and most likely only the ones derived from std::exception).

Manux
+3  A: 

Since you're not catching the exception within the context of the function, the function will terminate and the stack will be unwound as it looks for an exception handler (a catch block that would match either string, or the generic catch(...)). If it doesn't find one, your program will terminate.

Uncle Mikey
+1 for including mention of unwind. includes things like allocated objects will have destructors called.
Greg Domjan
+1  A: 

This maybe a good starting point to understanding exceptions. Exception handling in C++

DumbCoder