Should I use a try/catch statement with the DataAdapter.Fill method?
using (SqlConnection sqlConn = new SqlConnection(XYZ.Globals.ConnectionString))
{
using (SqlDataAdapter adapter = new SqlDataAdapter())
{
SqlCommand command = new SqlCommand("selCompanies", sqlConn)
{
CommandType = CommandType.StoredProcedure
};
command.Parameters.AddRange(searchParams.ToArray());
adapter.SelectCommand = command;
DataSet ds = new DataSe开发者_如何学运维t();
adapter.Fill(ds);
return ds;
}
}
Do I need to wrap the `adapter.fill()` in try catch finally block?
You only wrap things in a try/catch
when you can handle whatever exceptions it throws. If you can't, there's no need to put it in a try/catch
block.
The using
statement is equivalent to a try/finally
block.
The question would be what would I do differently if something went wrong. Typically, the correct action is to just let the exception raise upwards - after all, you weren't expecting an exception, so you can't do anything useful with it. The only subtlety here is IDisposable
, where you actively want to clean things up as you go; so using
statements for things like SqlConnection
, SqlCommand
, SqlDataReader
etc are ideal (But that is try
/finally
, not try
/catch
). So the main change I would make tour code would be to dispose the command:
using (SqlDataAdapter adapter = new SqlDataAdapter())
using (SqlCommand command = new SqlCommand("selCompanies", sqlConn))
{
command.CommandType = CommandType.StoredProcedure;
//...snip...
}
That depends on whether this code is wrapped for exception handling at a higher level. At what scope do you want to handle errors in this logic - typically this would be for a given 'block' of logic, not for each function call. Handling DB errors is a good idea in general.
In any case, you do need to have another using
on your SqlCommand
or you will leak it.
The same applies this adapter.Fill()
as to any other line of .net code:
If you have a good reason for catching and handling one particular exception, then catch it and handle it. If you don't have a good reason, don't catch it.
I don't see why this particular line should be error-handled in a specific way.
You only need to catch the exception from the fill here if you have error handling that will require the connection or command to be in scope.
Also, technically the adapter and the command will go out of scope as soon as you exit the using block for the connection. In many cases, this is probably sufficient to release those resources (the connection is the most valuable resource in most scenarios, since it creates overhead on the database server). It doesn't hurt to be explicit, though, especially if you're going to create multiple commands or adapters for the same conntection.
精彩评论