c# - try catch 的行为,最后在 c# 中使用 return 语句工作流程

标签 c# .net exception try-catch finally

我对这种 try、catch 和 finally with return 语句工作流毫无疑问...

此函数用于检索员工请假信息以供主管查看。它工作得很好,但如果找到 if 语句的数据,它将返回,否则将返回 else block 。即使两者都得到返回,它也会最终声明。 不知道为什么?

这里是代码片段:

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

问候 萨尔瓦

最佳答案

finally 语句总是被执行,即使没有异常发生也是如此。

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. 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.

关于c# - try catch 的行为,最后在 c# 中使用 return 语句工作流程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15659467/

相关文章:

c# - 如何获取 OPC 服务器上的标签列表

c# - Razor 中枚举下拉列表的显示名称

c# - 对 API 的异步请求,使用 yield 迭代器?

ruby-on-rails - Rails API 应用程序的异常(exception)政策

c# - 静态抛出类 : good or bad practice

c# - 使用NEST使用ElasticSearch 2.x搜索多种类型时,如何得到混合结果?

.net - Visual Studio/SOAP - 'Add Service Reference' 与 'Add Web Service Reference'

.NET Image.RemovePropertyItem 无明显效果

c# - 从零开始的基于 token 的WebAPI理论

android:如何在错误时正确退出应用程序