Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

try/catch around reference assignment

I would like to catch an exception from a method that returns a reference, without catching the same exception from a later call which uses the reference. For example:

try {
    Something &o = myMap.at(myIndex);
    foo(o);
} catch(std::out_of_range &e) {
    // If this was thrown by myMap.at, we can handle it
    // If this was thrown by foo, we can't, and need to propagate it
}

So I'm looking to do something like this:

Something &o;
try {
    o = myMap.at(myIndex);
} catch(std::out_of_range &e) {
    // Handle the error
}
foo(o);

But of course, that's not valid. I can think of ways to wrap foo's exceptions in another exception then unwrap it outside the try, but that's rather messy. Is there a better way?

MCVE can be found here: https://ideone.com/DJHxpO

like image 736
Dave Avatar asked Jun 18 '26 09:06

Dave


2 Answers

You can use an immediately invoked lambda expression:

Something &o = [&]() -> decltype(auto) {
    try {
        return myMap.at(myIndex);
    } catch(std::out_of_range &e) {
        // Handle the error
        // Return some other object for o to refer to.
    }
}();
foo(o);
like image 72
chris Avatar answered Jun 20 '26 21:06

chris


You can use pointer instead:

Something *o; // initialize it with nullptr if necessary
try {
    o = &myMap.at(myIndex);
} catch(std::out_of_range &e) {
    // Handle the error
}
foo(*o);      // check whether it's nullptr before dereference if necessary
like image 33
songyuanyao Avatar answered Jun 20 '26 23:06

songyuanyao



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!