Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens when I throw an exception?

Tags:

c++

exception

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?

like image 866
helloWorld Avatar asked Jun 17 '10 20:06

helloWorld


3 Answers

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 https://isocpp.org/wiki/faq/exceptions for more info.

like image 121
Cogwheel Avatar answered Nov 06 '22 15:11

Cogwheel


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.

like image 33
Adrian Petrescu Avatar answered Nov 06 '22 15:11

Adrian Petrescu


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.

like image 25
Michael Scott Shappe Avatar answered Nov 06 '22 15:11

Michael Scott Shappe