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

Bos*_*sak 14 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
}
Run Code Online (Sandbox Code Playgroud)

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

Jon*_*eet 26

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

不要只返回一个值,否则你永远不会发现你的世界是否是颠倒的.


The*_*ias 12

UnreachableException.NET 7为此目的引入了新类,正如我刚刚通过观看 Nick Chapsas 的 YouTube 视频The new .NET Exception that should NEVER be throwed 了解到的那样

throw new UnreachableException();
Run Code Online (Sandbox Code Playgroud)


Mat*_*ser 9

在以下情况之后使用以下内容显示逻辑失败消息foreach:

System.Diagnostics.Debug.Fail("Unreachable code reached");
Run Code Online (Sandbox Code Playgroud)

这将在调试期间提醒您.

此外,还在生产过程中抛出异常:

throw new InvalidOperationException();
Run Code Online (Sandbox Code Playgroud)

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

  • 使用Debug.Fail和异常是一个好主意; 这就是说异常并不打算成为可执行的代码路径.但是我会选择比"新例外"更好的例外.乔恩建议`InvalidOperationException`这似乎是合理的. (5认同)

Mic*_*ter 5

我认为每种情况都是不同的,但是,是的,最终你必须返回一些东西或抛出异常。在代码示例中处理此问题的方法只是从数组中删除 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;
}
Run Code Online (Sandbox Code Playgroud)


Bil*_*egg 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;
}
Run Code Online (Sandbox Code Playgroud)