2

私はこの試行、キャッチ、そして最後にreturnステートメントワークフローについてほとんど疑いがありません...

この機能は、上司が表示するために従業員の休暇情報を取得するために使用されます。これは非常にうまく機能しますが、ifステートメントのデータが見つかった場合はそれが返され、そうでない場合はブロックが返されます。両方がリターンを取得したとしても、それは最終的にステートメントになります。どうしてか分かりません?

ここのコードスニペット:

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

サルバよろしく

4

3 に答える 3

10

最後に、例外が発生しなくても、ステートメントは常に実行されます。

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

通常、finallyブロックのステートメントは、コントロールがtryステートメントを離れるときに実行されます。制御の転送は、通常の実行、break、continue、goto、またはreturnステートメントの実行、またはtryステートメントからの例外の伝播の結果として発生する可能性があります。

于 2013-03-27T13:02:54.040 に答える
3

finallyブロックは、例外がスローされたかどうかに関係なく、常に実行されるように設計されています。

于 2013-03-27T13:03:03.237 に答える
1

最終ブロックはすべての場合に実行されます。

于 2013-03-27T13:04:51.860 に答える