Hi there,
I think everyone who posted before me has mentioned everything that you want to know :)
Just adding to that, think of
finally
block as something you want to do regardless what happens inside a try block (E.g.: Exception thrown, Return statement found, everything went smoothly, etc.)
The easiest is to explain it with some code.
SqlConnection connection = null;
try {
var connectionStringName = connectionComboBox.Text.Trim();
if (connectionStringName.Length == 0) {
MessageBox.Show("Please, select a connection");
return;
} else {
connection = new SqlConnection();
connection.ConnectionString = ConfigurationManager.ConnectionStrings[connectionStringName].ToString();
connection.Open();
}
}
catch {
}
finally {
if ((connection != null) && (connection.State == ConnectionState.Open)
try {
connection.Close();
}
catch {
}
}
In the above example, there are multiple instances where exceptions might be thrown, even while opening a connection. Regardless of that, you want to
close the connection to the database,
IF there is a connection open after the code block executes. The finally block will execute, even if the
return
statement is executed.
One important thing to remember is, a
finally
block
MUST NOT throw an exception unless the system design explicitly wants you to do so, which is considered bad practice in general.
Hope this helps :) Regards