使用方法获取编译错误:“并非所有代码路径都返回值”

时间:2013-09-03 20:32:16

标签: c# asp.net methods compiler-errors boolean

我无法弄清楚为什么我不断收到编译错误:"并非所有代码路径都返回值"。我正在编写一个简单的类方法,如果帐户可用,则返回true;如果帐户不可用或为null / empty,则返回false。该方法的代码如下:

public static bool AccountAvailable(int AccountId)
{
    try
    {            
        bool accountavailable;

        string queryTransaction = "Select Count(AccountID) FROM Accounts WHERE AccountID = " + AccountId.ToString() + " AND AccountUsed = 0";

        //grab a connection to the database
        Database database = DatabaseFactory.CreateDatabase();

        //create an instance of the command
        DbCommand command = database.GetSqlStringCommand(queryTransaction);

        object dataobject = command.ExecuteScalar();

        if (dataobject == null || string.IsNullOrEmpty(Convert.ToString(dataobject)))
        {
            accountavailable = false;
        }

        else if (Convert.ToInt32(dataobject) == 0)
        {
            accountavailable = false;
        }

        else if (Convert.ToInt32(dataobject) > 0)
        {
            accountavailable = true;
        }

        else
        {
            accountavailable = true;
        }

        return accountavailable;
    }

    catch
    {

    }
}

对此有任何帮助或建议将不胜感激。谢谢!

3 个答案:

答案 0 :(得分:2)

如果在返回值之前代码中抛出异常,则控制将移至catch块。然后它到达方法的末尾而不返回任何内容。

返回catch块内或之后的内容。

答案 1 :(得分:1)

在catch块中,添加一个返回:

catch (Exception ex)
{
    // your code
    return null;
}

答案 2 :(得分:0)

建议尝试此代码

public static bool AccountAvailable(int AccountId)
{
    bool accountavailable = false;
    try
    {            

        string queryTransaction = "Select Count(AccountID) FROM Accounts WHERE AccountID = " + AccountId.ToString() + " AND AccountUsed = 0";

        //grab a connection to the database
        Database database = DatabaseFactory.CreateDatabase();

        //create an instance of the command
        DbCommand command = database.GetSqlStringCommand(queryTransaction);

        object dataobject = command.ExecuteScalar();

        if (dataobject == null || string.IsNullOrEmpty(Convert.ToString(dataobject)))
        {
            accountavailable = false;
        }

        else if (Convert.ToInt32(dataobject) == 0)
        {
            accountavailable = false;
        }

        else if (Convert.ToInt32(dataobject) > 0)
        {
            accountavailable = true;
        }

        else
        {
            accountavailable = true;
        }

    }

    catch
    {

    }
    return accountavailable;
}