Reputation: 2140
I return a nickname below, but Visual Studio keeps giving me the error: Not all code paths return a value.
What am I doing wrong? I am returning a nickname... Anyone who can help me further? Couldn't find a solution on Google though...
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();
}
}
Upvotes: 1
Views: 193
Reputation: 22814
In the exception handling bit, nothing's returned. Here's a fix.
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();
}
}
Upvotes: 3
Reputation: 3935
Try using this:
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;
}
Upvotes: 0
Reputation: 4733
You have declared method of type string, but if you will get an exception in one of the following lines:
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());
you won't return anything because there will be jump to catch clause where you don't have a return statement.
The best practice (IMO) would be placing the return statement outside of try..catch..finally
block and declaring returned variable at the beginning of the method (and initializing it with some default value)
Upvotes: 0