我有一个函数,它基本上从vectorusing返回一个元素at(size_type pos)。在无效(out_of_range)位置的情况下at()抛出std::out_of_range异常。
我基本上希望将此异常传播给调用者,以便可以在该级别上进行处理。我添加到我的吸气剂中的重新抛出是否有必要?或者我会通过完全省略来获得相同的效果try-catch?
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&){}
Run Code Online (Sandbox Code Playgroud)
我两个都试过了,没有发现任何区别,但我想知道我是否幸运,或者这是否有保证。
小智 5
抛出的异常std::vector::at(),与任何其他异常一样(如果我错了,有人纠正我),将展开堆栈,直到它到达捕获它的 try-catch 块,或者如果它没有被捕获,则会导致未处理的异常错误任何级别。
因此,如果您的唯一目的是在调用者级别捕获它,而无需任何中间异常处理,则无需就地捕获并重新抛出它:它将到达调用者的 try-catch 块,前提是没有中间的 try-catch块处理它。
| 归档时间: |
|
| 查看次数: |
50 次 |
| 最近记录: |