[英]What should I return in an error case in a function expected to return a Template<T> value?
I'm quite noob yet in OOP and is my first time handling exceptions and Templates, may be I planned the function in a wrong way... But I would like to know what should I return in this case if the execution goes wrong and the exception is thrown.... what kind of data error return in a function returning a Template? 我在OOP中还算是新手,这是我第一次处理异常和模板,可能是我以错误的方式计划了函数……但是我想知道如果执行出错并在这种情况下应该返回什么?引发异常。...返回模板的函数中返回哪种数据错误? Sorry if I am not clear enough, english is not my mothertongue...
抱歉,如果我不太清楚,英语不是我的母语。
template<typename T>
const T& List<T>::Next()
{
try
{
if (_actual->getNext() == NULL)
throw out_of_range("No next elements, list out of bounds");
else
{
_actual = _actual->getNext();
_Position++;
return _actual->getData();
}
}
catch (out_of_range &e)
{
cerr << "Error, " << e.what() << endl << "Position: " << _Position << " Elements: " << _Elements << endl;
}
// <--- what should I return here?? return NULL;? return 0;? return <T> thrash;??
}
If there's nothing to return then there's nothing to return. 如果没有退货,那就没有退货。
Let the exception propagate, either by not catching it here , or by re-throwing it after your cerr
statement with the throw
statement: 让异常传播,方法是不在此处捕获它 ,或者在您的
cerr
语句之后使用throw
语句将其重新throw
:
catch (out_of_range &e)
{
cerr << "Error, " << e.what() << endl
<< "Position: " << _Position
<< " Elements: " << _Elements << endl;
throw;
}
Your next question will be how to handle the exception in the calling scope. 您的下一个问题将是如何在调用范围内处理异常。 :)
:)
But at least you won't have to worry about return values any more. 但是至少您不必再担心返回值了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.