The answer to this question has already been posted, but no one has really addressed the "why" of it so in the interest of teaching a man to fish, I am going to add this answer.
The reason you are getting the error about not all paths returning a value is because not all paths return a value. Sorry, but it means exactly what it says. You have a method that says it will return a boolean value. That is a contract that you have agreed to honor, yet your code does not honor that contract. It doesn't return a value. Even if you put a return inside your try statement, that won't be enough because there might be a time when your code throws an error before they try statement finishes. In that case, the return statement would be skipped and that path would not have a return value.
You could put multiple return statements in (two, in this case) to cover all the code paths, but that gets messy in a larger application. Instead, what I like to do is create a variable called output that is the return type. In your case, this would mean that output would be a
boolean
. At the very top of the application, I initialize the output variable to have a value that conveys an error. In this case, that would mean that it would be false. Then, at the very end of my method, outside of any limiting code block like try/catch statements, I return the output value. This way, if something goes wrong, no matter where it happens, the error value will be returned. I then set the value to true if, and only if, the criteria has been met to make the method a success. Here is a demo, with your code, on how that would work:
public bool GetPerson(int PersonID,string PersonEmailID )
{
bool output = false;
try
{
conn.Open();
cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = "sp_UPerson";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@PersonID", PersonID);
cmd.Parameters.AddWithValue("@PersonEmailID ", PersonEmailID );
int recordCount = cmd.ExecuteNonQuery()
if (recordCount > 0)
{
output = true;
}
}
catch
{
}
finally
{
conn.Close();
}
return output;
}
Now we have one variable that holds the state of our method. We also only have one place where our code exits. Finally, we know that no matter what, our return value will be valid. We will never tell the calling method that we were successful when we were not.
The one final thing I want to cover is the
boolean
return value. I don't think that this is a good idea. If you are writing records to SQL, you should get back the number of records affected. This allows you to test situations where you don't want any rows affected. Right now, that would mean that your method would say you had an error but that isn't true. Unless you have a strong business case why you must have a
boolean
return value, I would recommend changing it to be an
int
. If you cannot do that, I would recommend taking out the
if
statement and returning true if the application didn't crash.