带有循环和异常的return语句

时间:2017-09-01 20:05:10

标签: c++

我有一个抛出的API,我必须在失败前重试一定次数。我的代码如下:

bool bar(int i) 
{
    // edit: missed the 'if' 
    if(i == 4) return true; 
    throw std::runtime_error("error");
}

bool foo() 
{
    for(int i = 0; i < 5; ++i)
    {
        try
        {
            return bar(i); // cannot change implementation
        }
        catch(...)
        {
            if(i <4) continue;
            throw;
        }
    }
}

int main() 
{
    std::cout << foo();
}

我收到以下错误:

warning: control reaches end of non-void function [-Wreturn-type]

为什么我收到这个警告?它看起来很安全。

1 个答案:

答案 0 :(得分:1)

看起来你正在使用的任何编译器都无法弄清楚你的for()循环中i的值永远不会达到5。在一般情况下,这是一个很多要问的问题。编译器,即使在这种情况下对人类观察者来说很明显。