我使用 try{} catch(){} 来处理返回模板类型的函数中的错误。
T get (int iOffset) const
{
try {
checkIndex(iOffset);
}
catch (char const* msg) {
std::cout << msg << std::endl;
}
int index = (m_iReadIdx + iOffset) % m_iBuffLength;
float a = m_ptBuff[index];
return a;
}
该函数将首先调用checkIndex
来检查输入是否超出范围,如果超出则抛出错误。
但是,如果checkIndex
抛出错误,我不希望外部get
返回任何值,因为返回值可能被其他函数使用或打印不正确.如果我在 catch block 中放一个 return,我不知道要返回什么,因为它是一个模板。如果我不这样做,catch block 之后的代码仍会执行并因此返回一个值。
有什么办法吗?我是 C++ 的新手,想知道人们通常如何在这种情况下进行错误处理?谢谢!
最佳答案
However, I don't want the outside get return any value if checkIndex throws an error, because the returned value may be used by other functions or printed out incorrectly.
你总是可以在记录后重新抛出异常
T get (int iOffset) const
{
try {
checkIndex(iOffset);
}
catch (char const* msg) {
std::cout << msg << std::endl;
throw; // Just re-throw the exception
}
int index = (m_iReadIdx + iOffset) % m_iBuffLength;
float a = m_ptBuff[index];
return a;
}
关于C++ 捕获错误并退出函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48549095/