In the Delphi world, it was considered by some, at least, preferable to put the try AFTER a resource allocation, such as:
OracleCommand oc = new OracleCommand(query, con);
try
begin
oc.CommandType = CommandType.Text;
String s = oc.ExecuteScalar().ToString();
try
return s;
except (on OracleException ex)
begin
ShowMessage(ex.Message);
result := string.Empty;
end;
end
finally
begin
con.Close();
con.Dispose();
end;
Is it the same in C#, or should the “try” come prior to the resource allocation:
try
{
OracleCommand oc = new OracleCommand(query, con);
oc.CommandType = CommandType.Text;
String s = oc.ExecuteScalar().ToString();
try
{
return s;
}
catch (OracleException ex)
{
MessageBox.Show(ex.Message);
return string.Empty;
}
}
finally
{
con.Close();
con.Dispose();
}
?
There’s an even better solution: the using statement. Instead of this code, you can write the idiomatic