简体   繁体   English

try catch的行为,最后是c#中的return语句工作流

[英]behaviour of try catch and finally with return statement workflow in c#

I have little doubt about this try, catch and finally with return statement workflow... 我对这个尝试,捕获以及最后使用return语句工作流程毫无疑问......

This function is used to retrieve employee leave information for supervisor view. 此功能用于检索主管视图的员工休假信息。 It works very well, but if there data found for if statement it will be return otherwise else block will be return. 它工作得很好,但如果找到if语句的数据,它将返回,否则块将返回。 Even if the both get returns, its going to finally statement. 即使两者都获得了回报,它也会最终声明。 I don't know why? 我不知道为什么?

Code snippet here: 这里的代码片段:

List<Leave> ILeaveData.GetLeaveForSupervisorView(int userID)
{
    SqlConnection con = new SqlConnection(_connectionString);
    SqlCommand cmd = new SqlCommand("Storeprocedurename", con);
    cmd.CommandType = CommandType.StoredProcedure;

    cmd.Parameters.Add(new SqlParameter("@Id", SqlDbType.Int));
    cmd.Parameters["@Id"].Value = userID;

    // Get employee leave information

    try
    {
        con.Open();
        DataSet ds = new DataSet();
        SqlDataAdapter adapter = new SqlDataAdapter();
        adapter.SelectCommand = cmd;
        adapter.Fill(ds);


        if (ds.Tables[0].Rows.Count > 0)
        {
            List<Leave> leave = new List<Leave>();
            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
            {
                leave.Add(CreateLeaveForAdminViewFromDataRow(ds.Tables[0].Rows[i]));
            }
            return leave; // if data found then statement return here
        }
        else
        {
            return null; // otherwise return here
            // throw new Exception("Data Error");
         }
      }
      catch (SqlException err)
      {
          IErrorLog elog = new ErrorLog(_connectionString);
          elog.LogSystemError(err);
          throw new ApplicationException("Data Error", (Exception)err);
      }
      finally
      {
          if (con != null)
          {
              con.Close();
          }
       }
   }

regards Sarva 关于萨尔瓦

Finally statements are always executed, even if no exception occurs. 最后,即使没有异常发生,也始终执行语句。

http://msdn.microsoft.com/en-gb/library/zwc8s4fz(v=vs.110).aspx : http://msdn.microsoft.com/en-gb/library/zwc8s4fz(v=vs.110).aspx

Typically, the statements of a finally block run when control leaves a try statement. 通常,当控件离开try语句时,finally块的语句会运行。 The transfer of control can occur as a result of normal execution, of execution of a break, continue, goto, or return statement, or of propagation of an exception out of the try statement. 控制权的转移可以是正常执行,执行break,continue,goto或return语句,或者从try语句中传播异常的结果。

finally块旨在始终执行,无论是否抛出异常。

在所有情况下都将执行最终块。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM