当我被迫编写无法访问的代码时,我该怎么办?

时间:2013-06-06 15:45:07

标签: c# exception unreachable-code

我有这段简单的代码:

public static int GetInt(int number)
{
    int[] ints = new int[]{ 3, 7, 9, int.MaxValue };
    foreach (int i in ints)
        if (number <= i)
            return i;

    return int.MaxValue; //this should be unreachable code since the last int is int.MaxValue and number <= int.MaxValue is allways true so the above code will allways return
}

问题是编译器说不是每个执行路径都返回一个值。所以我必须编写永远不会达到的代码。我的问题是,在这样的情况下我该怎么办?我应该返回一些默认值还是应该抛出异常。另外,如果我想抛出异常,什么异常适合抛出?我找不到类似UnreachableCodeException的内容。

7 个答案:

答案 0 :(得分:24)

我很想使用InvalidOperationException - 或其他一些你不会明确捕获的异常。给它一条消息,表明你真的不希望到达这里。这是一个“世界严重破碎”的失败。 InvalidOperationException并没有完全捕捉到这一点,但我无法想到更好的一个。当然,您总是可以在整个代码库中创建自己的例外。

不要只返回一个值,否则你永远不会知道你的世界是否是颠倒的。

答案 1 :(得分:8)

使用以下内容在foreach

后显示逻辑失败消息
System.Diagnostics.Debug.Fail("Unreachable code reached");

这将在调试期间提醒您。

此外,还要在制作过程中抛出异常:

throw new InvalidOperationException();

不要只返回一个值,特别是一个可能有效的值:你永远不会捕获逻辑错误。

答案 2 :(得分:5)

不是从循环返回,而是声明一个返回值变量,设置它,然后在代码末尾返回一次。

public static int GetInt(int number)
{
    var rtnVal = int.MaxValue;
    int[] ints = new int[]{ 3, 7, 9, int.MaxValue };
    foreach (int i in ints) {
        if (number <= i) {
            rtnVal = i;
            break;
        }
    }
    return rtnVal;
}

答案 3 :(得分:4)

我认为每个案例都不同,但是,最终你必须返回一些内容或抛出异常。在代码示例中处理此问题的方法只是从数组中删除int.MaxValue:

public static int GetInt(int number)
{
    int[] ints = new int[]{ 3, 7, 9 };
    foreach (int i in ints)
        if (number <= i)
            return i;
    return int.MaxValue;
}

答案 4 :(得分:2)

这是一个LINQ选项,可以在找不到匹配项时自动抛出异常

public static int GetInt(int number)
{
    int[] ints = new int[]{ 3, 7, 9, int.MaxValue };
    return ints.First(i => number <= i);
}

答案 5 :(得分:1)

编译器无法判断您的 foreach 循环将始终返回值。

理论上的编译器可以这样做,因为原则上信息是可用的,但C#编译器不能。

答案 6 :(得分:0)

为什么不直接返回大于数字的第一个值

    public static int GetInt(int number)
    {
        var ints = new[] { 3, 7, 9};
        return (ints.Any(i => i > number))? 
            ints.First(i => i > number): int.MaxValue;
    }
相关问题