Search code examples
c++error-handlingtry-catchthrow

Properly handling an exception


My understanding is that in modern C++, it is preferable to use throw instead of returning an error code. That is to say, if I have some function:

void MyFunction(int foo, double bar){
    // Do some stuff....

    if (exception_criteria_met){
        throw "Call to MyFunction with inputs" << foo << " and " << bar << " failed because ...";
    }
};

Does this mean that, in order to properly handle this, then in all functions that make a call to MyFunction, I must implement something like:

void MyOuterFunction(int foo){
    // Do some stuff...

    try {
        MyFunction(foo, bar);
    } catch (const char * exception_message) {
        throw "Call to MyOuterFunction with inputs " << foo << " failed because call to MyFunction with ....";
    };

And then wouldn't that imply that I must perform this same kind of error handling all the way down through all functions that calls into this stack of function calls? Obviously at some point, maybe one of the functions can actually handle the exception and not need to throw an exception of its own, but perhaps just print a warning or something similar. But how do you keep this organized and intelligible? It seems like a remarkably complicated thing to think all the way through when you've got many functions interacting with one another.

(As a secondary question, if MyFunction(foo,bar) were to return a value that I wanted to use, wouldn't it mean that after leaving the try { } block, the returned value would fall out of scope? Does that imply I should avoid using function return values if I'm going to be using try-catch?)


Solution

  • I think most of your question is either too broad or opinion based or both. However, your confusion seems to start with

    then in all functions that make a call to MyFunction, I must implement something like:

    That's not right.

    The function calling MyFunction that potentially throws can look like this:

    void MyOuterFunction(int foo){
        // Do some stuff...
        MyFunction(foo, bar);
    };
    

    If you would have to always catch an exception immediately, exceptions would be rather impractical. Thats not how they work.

    In a nutshell: The exception continues to travel up the call stack until you either catch it or main is reached and it is still not caught, in that case the program terminates.

    There is no fixed rule where you should catch the exception. My personal rule of thumb is to catch it when it is possible to recover from it, but not sooner. Sometimes not catching an expection at all is the most viable. Catching and rethrowing is rarely useful and catching it only to rethrow as you do is never useful to my knowledge.