Sarvaratchagan
Sarvaratchagan

Reputation: 95

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

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

Upvotes: 2

Views: 2265

Answers (3)

Darren
Darren

Reputation: 70776

Finally statements are always executed, even if no exception occurs.

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.

Upvotes: 10

Mahesh KP
Mahesh KP

Reputation: 6446

Final block will be executed in all cases.

Upvotes: 1

Ilya Ivanov
Ilya Ivanov

Reputation: 23646

finally block is designed to always execute, regardless of whether exception has been thrown or not.

Upvotes: 3

Related Questions