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
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);
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With