因为如果出现异常的话那么你的这个函数就没有任何返回值了。所以你最好将return 语句写在finally语句里

解决方案 »

  1.   

    catch和finally都没有设置返回值所以出现的问题!
      

  2.   

    如果try里面出现异常你的函数就没有返回值了
    在finally里机上 return ""或别的什么你要的返回值。
      

  3.   

    private string getCodeName(string strCn)
    {
    string ccc;
    string strConn = "Server = kfsh-1;user id = sa; password = mix; initial catalog = hx;Connection Timeout = 5";
    SqlConnection conn = new SqlConnection(strConn);
    conn.Open(); string select = "SELECT c_code FROM citycode WHERE c_name like '%" + strCn + "'";
    try
    {
    SqlCommand cmd = new SqlCommand(select, conn);
    // Object cc;
    ccc = cmd.ExecuteScalar().ToString();
    return ccc; }
    catch(SqlException sex1)
    {
    MessageBox.Show(sex1.Message,"error1",MessageBoxButtons.OK);
    }
    finally
    {
    conn.Close();
                                         //增加的行
                                         return ""; }
    }
    在conn.Close()前检查下conn是否为null 是个好习惯
      

  4.   

    出现问题的原因是当扑捉到异常后,没有再次抛出异常,加个 throw 就行了,
    建议楼主这样写,private void button1_Click(object sender, System.EventArgs e)
    {
    string cName = textBox1.Text;string cc = getCodeName(cName);
    label1.Text = cc;}
    private string getCodeName(string strCn)
    {
    string ccc;
    string strConn = "Server = kfsh-1;user id = sa; password = mix; initial catalog = hx;Connection Timeout = 5";
    SqlConnection conn = new SqlConnection(strConn);
    conn.Open();string select = "SELECT c_code FROM citycode WHERE c_name like '%" + strCn + "'";
    try
    {
    SqlCommand cmd = new SqlCommand(select, conn);
    // Object cc;
    ccc = cmd.ExecuteScalar().ToString();
    return ccc;}
    catch(SqlException sex1)
    {
      throw new Exception("执行Sql语句错误",sex1);
    }
    finally
    {
    conn.Close();
    }
    }
    如果想不再次抛出异常,那把return放到最后,建议楼主抛出异常,这样符合设计模式,并且处理更好。
      

  5.   

    private string getCodeName(string strCn)
    方法根本就没有返回值,当然绘出错了.