0

I have a function that basically returns an element from a vector using at(size_type pos). at() throws an std::out_of_range exception in case of an invalid (out_of_range) position.

I basically want this exception to be propagated to the caller, so that it can be handled on that level. Would the rethrow that I've added to my getter be necessary? Or would I get the same effect by just omitting the try-catch altogether?

int MyClass::GetNumber(size_t a_Idx) const
{
    // Is the following try-catch-rethrow necessary? Or can the whole try-catch be omitted?
    try
    {
        return m_Numbers.at(a_Idx);
    }
    catch (const std::out_of_range&)
    {
        // A throw expression that has no operand re-throws the exception currently being handled
        throw;
    }
}

MyClass m;

try
{
    int t = m.GetNumber(42);
}
catch(const std::out_of_range&){}

I tried both, and didn't notice any difference, but I wonder whether I'm lucky, or whether this is guaranteed.

1
  • Yes, you'd get the same effect without the try block inside MyClass::GetNumber. That's the point of exceptions: if you don't need to deal with it locally, you don't need to write any code for it. May 15, 2020 at 15:03

2 Answers 2

5

The exception thrown by std::vector::at(), as any other exception (someone correct me if I'm wrong), will unwind the stack until it reaches a try-catch block where it is caught, or cause an unhandled exception error if it isn't caught at any level.

Therefore, if your only intent is to catch it at the caller level, without any intermediate exception handling, there is no need to catch it in place and rethrow it: it will reach the caller's try-catch block, provided no intermediate try-catch block handles it.

1
  • @Ben Take a look at assembly generated by two different versions, in your case exception handling doubles number of instructions used (in case there is no exception you get +1 jmp). link May 15, 2020 at 15:01
1

It's guaranteed.

Exceptions bubble up until something catches them… unless nothing catches them, then your program aborts instead.

So, you do not need to explicitly re-throw through each scope.

Re-throwing would be useful if you had some extra work to do in that catch block before proceeding to let the exception bubble up as it was going to anyway.


Don't forget to note in your documentation that GetNumber(size_t) can throw std::out_of_range.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.