C# - 唯一的“并非所有代码路径返回值”问题

时间:2016-05-17 19:15:21

标签: c#

我有public static IPAddress

这是我的代码:

try {
            IPAddress[] addresslist = Dns.GetHostAddresses(Website);

            foreach (IPAddress theaddress in addresslist)
            {
                return theaddress;
            }
        }
        catch
        {
            return IPAddress.Parse("Invalid Website!");
            /* dont worry about the line of code above this */
        }

问题是我的所有可能的代码路径都返回一个值。

我要做的是将网站地址解析为互联网协议地址,如果这很重要的话。我不确定Try,Catch,Finally方法是否可以解决这个问题,如果Try,Catch,Finally方法可以修复它,我将如何使用它?在此先感谢:)

2 个答案:

答案 0 :(得分:0)

因为看起来您只返回返回类型为IPAddress

的第一个项目

你可以这样做:

try
{ 
    return Dns.GetHostAddresses(Website).FirstOrDefault();
}
catch(Exception x)
{
    throw new Exception("Invalid website", x);
}

如果集合恰好为Empty,则它将返回null。或者,如果您希望它为未找到的情况抛出异常。

try
{ 
    return Dns.GetHostAddresses(Website).First();
}
catch(InvalidOperationException iox)
{
    throw new Exception("IP list was empty", iox);
}
catch(Exception x)
{
    throw new Exception("Invalid website", x);
}

答案 1 :(得分:-1)

这是一种方法。您所遇到的问题是,编译时不知道Dns.GetHostAddresses(Website)是否返回new IPAddress[0]

try 
{
    IPAddress[] addresslist = Dns.GetHostAddresses(Website);

    foreach (IPAddress theaddress in addresslist)
    {
        return theaddress;
    }
}
catch
{
    return IPAddress.Parse(DefaultIP);
}

return null;

基于代码的更好的解决方案是。

try 
{
    IPAddress[] addresslist = Dns.GetHostAddresses(Website);
    return addresslist.FirstOrDefault();
}
catch
{
    return IPAddress.Parse(DefaultIP);
}

或者如果你的foorloop做了一些神奇的事情,那就扔掉并抓住空列表。

try 
{
    IPAddress[] addresslist = Dns.GetHostAddresses(Website);
    if(!addresslist.Any())
    {
        //Since you promise that it will never be empty then this is a exceptionable offence.
        throw new Exception("Host address list is empty");
        //But a simpler solution is just to return something.
    }
    foreach (IPAddress theaddress in addresslist)
    {
        return theaddress;
    }
}
catch
{
    return IPAddress.Parse(DefaultIP);
}