当我返回某些内容时,并非所有代码路径都返回值

时间:2013-06-16 09:47:57

标签: c# windows forms

我在下面返回一个昵称,但Visual Studio一直给我错误:并非所有代码路径都返回一个值。

我做错了什么?我回来了一个绰号......任何可以帮助我的人?虽然无法在Google上找到解决方案......

    public string GetEigenaarBlog(int gebruikerid)
    {
        try
        {
            connection.Open();
            string sql = "SELECT NICKNAME FROM GEBRUIKER WHERE GEBRUIKERID = :GEBRUIKERID";
            command = new OracleCommand(sql, connection);
            command.Parameters.Add(new OracleParameter(":GEBRUIKERID", gebruikerid));
            string nickname = Convert.ToString(command.ExecuteReader());
            return nickname;
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
        finally
        {
            connection.Close();
        }
    }

3 个答案:

答案 0 :(得分:3)

在异常处理位中,没有返回任何内容。这是一个修复。

public string GetEigenaarBlog(int gebruikerid)
{
    try
    {
        connection.Open();
        string sql = "SELECT NICKNAME FROM GEBRUIKER WHERE GEBRUIKERID = :GEBRUIKERID";
        command = new OracleCommand(sql, connection);
        command.Parameters.Add(new OracleParameter(":GEBRUIKERID", gebruikerid));
        string nickname = Convert.ToString(command.ExecuteReader());
        return nickname;
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
        return null; 
        //if you want to let the code know too put "throw;" here instead.
    }
    finally
    {
        connection.Close();
    }
}

答案 1 :(得分:0)

尝试使用:

 public string GetEigenaarBlog(int gebruikerid)
            {
          string nickname = null;
                try
                {
                    connection.Open();
                    string sql = "SELECT NICKNAME FROM GEBRUIKER WHERE GEBRUIKERID = :GEBRUIKERID";
                    command = new OracleCommand(sql, connection);
                    command.Parameters.Add(new OracleParameter(":GEBRUIKERID", gebruikerid));
                    nickname = Convert.ToString(command.ExecuteReader());           
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
                finally
                {
                    connection.Close();                   
                }
     return nickname;

            }

答案 2 :(得分:0)

您已声明类型字符串的方法,但是如果您将在以下某行中获得异常:

connection.Open();
string sql = "SELECT NICKNAME FROM GEBRUIKER WHERE GEBRUIKERID = :GEBRUIKERID";
command = new OracleCommand(sql, connection);
command.Parameters.Add(new OracleParameter(":GEBRUIKERID", gebruikerid));
string nickname = Convert.ToString(command.ExecuteReader());

你不会返回任何东西,因为在没有return语句的情况下会跳转到catch子句。

最佳实践(IMO)将return语句置于try..catch..finally块之外,并在方法开头声明返回的变量(并使用某个默认值初始化它)