我对这种 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/