10

异常return后对值有任何好处吗?throw如果没有,是否可以return省略该语句,是否可以以某种方式消除编译器错误C4715: not all control paths return a value

提前致谢。

编辑:(示例代码)

for (ushort i = 0; i < itsNumUnits; ++i)
    if (unitFormation[i] == unit)
    {
        return unitSetup[i];
    }
    else
        throw unit;

return 0;
4

4 回答 4

7

抛出异常后无需返回值。如果你有这个错误,你应该检查你的代码可以到达的路径而不抛出异常,例如

if (something)
    throw Exception;
else
    return value;

未能在 "if" 的 "else" 分支中返回值会导致编译错误,因为可能会或可能不会抛出异常,具体取决于something.

于 2010-06-24T12:40:34.993 回答
2

throw 本身终止函数执行。但是如果你的函数返回一个值,并且没有抛出异常,你就必须注意返回一个值。例如:

bool foo(bool _flag) throw(...)
{
    if (_flag)
    {
        throw "foo is throwing an exception";
    }
    return true;
}
于 2010-06-24T12:46:17.400 回答
0

与能够“返回”一个值以及抛出异常最接近的是当函数在抛出异常之前写入指针或引用对象时:

void my_func(int& ret)
{
    ret = 0;

    for (ushort i = 0; i < itsNumUnits; ++i) {
        if (unitFormation[i] == unit) {
            ret = unitSetup[i];
            return;
        }
        else {
            throw unit;
        }
    }
}

然而,这种模式很容易出错并且很少有用。使用前请仔细考虑。

于 2010-06-24T18:18:02.490 回答
-1

在 throw 之后你最终会被 catch (下面的代码 throw 没有被执行)。唯一被执行的块是finally。

如果您想实现上述目标,请执行以下操作:

object returnVal = null; // the bad
try
{
    //some code here
    throw new Exception(); // something bad happened
    //some more code
    returnVal = new object(); // the good
}
catch(Exception ex)
{
    // log, try to recover etc.
    // maybe it`s a good idea not to throw it away if you can handle it here!
}
return returnVal; // either the good or the bad (never the ugly!)

警告的 C# 等效项是编译器错误,因此无论如何我认为摆脱编译器警告不是一个好主意,而是尝试解决它们。

问候...

于 2010-06-24T12:50:09.800 回答