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.
try
block insideMyClass::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.