Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

error: Not All Code Paths Return A value?

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();
        }
    }
like image 208
Zarak Dawood Avatar asked Jun 15 '26 12:06

Zarak Dawood


1 Answers

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;
}
like image 121
atlaste Avatar answered Jun 18 '26 00:06

atlaste