Throwing an exception from a lambda expression, a bad habit?

I am currently parsing the token queue: instead of checking that the queue is empty for each subsequent one pop()

, I wrote a lambda, throwing an exception if queue.begin() == queue.end()

. I am wondering if this is a good, "correct" implementation, or if it is generally considered bad practice to throw an exception from the lambda expression?

+1


source to share


3 answers


Throwing an exception from a lambda function is equivalent to throwing an exception from any other function.



Now if it is good practice in such a context to throw an exception, in my humble opinion it is not. Exceptions are meant to be used in exceptional situations (like a bullet pierced your CPU), and I don't think reaching the end of the range qualifies as such (that is, exceptional).

+3


source


I think it depends on what you are trying to achieve. I personally would leave a check for an empty queue for the function that pop is called on. There seems to be no reason to limit the possibilities of your queue except. There might be some cases you want to handle when the queue is empty, but throwing an exception and handling that seems to be causing code bloat for me.



Just my preference.

+2


source


I asked myself this question while working on one of my projects.

I agree with the answers that say they can be used, but it is better to limit them to exceptional cases only (especially since exceptions are not cheap when thrown).

In my case, I used a lambda to save the file several times during the update process (the code for all the savings is the same, and if it doesn't work, I consider it an exception because it shouldn't happen).

The pseudocode of my project:

void upgradeFile(/* params */){

    std::string configVersion = readCurrentConfigVersion();

    auto fSaveFileAfterUpgrade = [](/* params */){
            if(!param1.saveFile(/*params*/)){
                throw std::runtime_error("My error Message");
            }
    };

    if(configVersion == "1.0"){

        const std::string versionAfterUpgrade = "1.1";

        // UPGRADE CODE...

        fSaveFileAfterUpgrade(/* params */);

        configVersion = versionAfterUpgrade;
    }

    if(configVersion == "1.1"){
        const std::string versionAfterUpgrade = "1.1a";

        // UPGRADE CODE...

        fSaveFileAfterUpgrade(/* params */);

        configVersion = versionAfterUpgrade;
    }
}

      

If an exception is thrown in the lambda, the function that calls updateFile will handle it (I'm setting it up to try).

0


source







All Articles