c#中try catch和return语句工作流的行为
本文关键字:工作流 语句 return try catch | 更新日期: 2023-09-27 18:06:20
我对这个try, catch, and finally with return语句的工作流程毫无疑问…
此函数用于检索员工休假信息以供主管查看。它工作得很好,但是如果找到了if语句的数据,它将被返回,否则将返回else块。即使两个都得到了返回,它也会是finally语句。我不知道为什么?
代码片段:
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();
}
}
}
的问候Sarva
Finally语句总是被执行,即使没有异常发生。
http://msdn.microsoft.com/en-gb/library/zwc8s4fz (v = vs.110) . aspx:
通常,finally块的语句在控制离开try语句时运行。控制的转移可以在下列情况下发生:正常执行、执行break、continue、goto或return语句,或者在try语句之外传播异常。
finally
块被设计为始终执行,无论是否抛出异常。
在任何情况下都将执行Final块。