I am Getting this Error (Not All Code Paths Return A Value). I want to insert data in my database with unique key constraint. but when i added this in my code my method is giving me this error.
Here is my code
public string Insert()
{
SqlConnection Conn = new SqlConnection(@"Data Source=ZARAK\SQLEXPRESS;Initial Catalog=ProjectDAL;integrated security=true");
try
{
Conn.Open();
SqlCommand cmd = new SqlCommand("Insert INTO tbl_User(Name,Email,Password) VALUES ('" + name + "','" + email + "','" + password + "')", Conn);
int restl = cmd.ExecuteNonQuery();
//temp = true;
return "Record Inserted successfully!";
}
catch (SqlException ex)
{
if (ex.Number == 2627)
{
return "Record Already Exists";
}
}
finally
{
Conn.Close();
}
}
Your problem is here:
catch (SqlException ex)
{
if (ex.Number == 2627)
{
return "Record Already Exists";
}
// **
}
If you look at the code paths of your application, each if also implicitly adds an else. In this case the else doesn't contain a return statement, hence the error.
And then there's exceptions...
Exceptions are there to handle exceptional cases. There's this implicit agreement amongst software developers that catch implies handle it appropriately.
One way to handle it is to inform the user that the record already exists (I'm guessing that's what you do). If another thing happens, it's not always productive to inform the user of the error; you might simply want to try again in a few seconds (deadlock) or do something else. Usually you handle code like that on a higher level, and let the exception ripple.
As a result, I cannot tell you what the code of ** needs to be; you need to decide that for yourself based on what you want to achieve.
For example:
catch (SqlException ex)
{
if (ex.Number == 2627)
{
return "Record Already Exists"; // user needs to do something
}
// We don't want to handle the rest here:
throw;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With