C # - Try-catch-finally on Return

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

Mostly I get active users in my database. But can someone explain to me whether the Finally block will execute if it successfully starts the try block and returns a DataTable ??

thanks

+13
source share
3 answers

Yes.

As indicated here: MSDN

Typically, the statements of the finally block are executed when the control leaves try to write. Control transfer may occur as a result of normal execution, interruption, continuation, transition, or return of an operator or the distribution of an exception from a try statement.

But finally, the block is not always executed. You can read the Alex Papadimulis joke here

+10
source

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

+2
source

the finally block is always executed.

you must delete in the finally block. Because, dispose also closes the connection and provides unmanaged memory resources.

 finally { connection.Dispose(); } 
+2
source

Source: https://habr.com/ru/post/1238938/


All Articles