处理未使用的 return 语句

Handling unused return statements

我有以下代码:

public static QHttpResponse SafeExecute(QHttpRequest request, int retries, int sleep)
{
    if (retries < 1)
        throw new Exception("retries must be at least 1");

    for (int index = 0; index < retries; index++)
    {
        try
        {
            return QWebClient.Execute(request);
        }
        catch (Exception)
        {
            if (index == retries - 1)
                throw;

            Thread.Sleep(sleep);
        }
    }

    return null;
}

此函数中的第二个 return 什么都不做。使用 return null 还是 throw new Exception("Shouldn't be here") 更好?

或者我应该通过将结果存储在变量中并 returning 来完全避免这种情况吗? (这似乎是不必要的)

是的,对于设计为不可到达的路径,抛出异常是有意义的。也作为一种明确的方式来记录这是您的方法的预期操作。

一个"InvalidLogicException"会很好,但不存在。

在 c# 中,最多 "appropriate" 种可用的异常类型可能是以下之一:

throw new InvalidProgramException("BUG: This code should be unreachable by design");
throw new InvalidOperationException("BUG: This code should be unreachable by design");
throw new NotSupportedException("BUG: This code should be unreachable by design");