加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 错误:并非所有代码路径返回值?

发布时间:2020-12-15 19:27:22 所属栏目:百科 来源:网络整理
导读:我收到此错误(并非所有代码路径返回值).我想用唯一键约束在我的数据库中插入数据.但是当我在我的代码中添加它时,我的方法给了我这个错误. 这是我的代码 public string Insert() { SqlConnection Conn = new SqlConnection(@"Data Source=ZARAKSQLEXPRESS;In
我收到此错误(并非所有代码路径返回值).我想用唯一键约束在我的数据库中插入数据.但是当我在我的代码中添加它时,我的方法给了我这个错误.

这是我的代码

public string Insert()
    {

        SqlConnection Conn = new SqlConnection(@"Data Source=ZARAKSQLEXPRESS;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();
        }
    }

解决方法

你的问题在这里:

catch (SqlException ex)
{
    if (ex.Number == 2627)
    {
        return "Record Already Exists";
    }
    // **
}

如果查看应用程序的代码路径,每个代码路径也会隐式添加其他内容.在这种情况下,else不包含return语句,因此错误.

然后是例外……

处理特殊情况的例外情况.软件开发人员之间存在这种隐含的协议,捕获意味着适当地处理它.

处理它的一种方法是通知用户记录已经存在(我猜这是你做的).如果发生了其他事情,通知用户错误并不总是有效的;你可能只想在几秒钟内再次尝试(死锁)或做其他事情.通常你会在更高级别上处理类似的代码,并让异常涟漪.

结果,我不能告诉你**的代码需要什么;你需要根据你想要达到的目标自己决定.

例如:

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;
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读