25

I have the following code:

public DataTable GetAllActiveUsers()
{
            DataTable dataTable = new DataTable();

            try
            {
                connection.Open();

                SqlCommand getAllActiveUsersCommand = new SqlCommand(getAllUsers, connection);

                SqlDataAdapter dataAdapter = new SqlDataAdapter(getAllActiveUsersCommand);
                dataAdapter.Fill(dataTable);

                return dataTable;
            }
            catch(Exception e)
            {
                Console.WriteLine(e);

                return null;
            }
            finally
            {
                connection.Close();
            }
        }

Which basically get's the active users I have on my database. But can someone explain to me whether the Finally Block will be executed if it successfully runs the try block and returns the DataTable??

Thanks

Danny
  • 9,199
  • 16
  • 53
  • 75

3 Answers3

20

Yes.

As stated here: MSDN

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.

But finally block is not always executed. You can read Alex Papadimoulis's anecdote here

gyosifov
  • 3,193
  • 4
  • 25
  • 41
5

Yes, it does.
The finally block will be executed whether there is a return statement or an exception thrown in the try {} catch() block.

croxy
  • 4,082
  • 9
  • 28
  • 46
3

finally block is always executed.

you should Dispose in finally block. Because, dispose also closes the connection and disposes unmanaged memory resources.

finally
{
    connection.Dispose();
}
mehmet mecek
  • 2,615
  • 2
  • 21
  • 25