why this is wrong with this finally

  • Thread starter Thread starter Ahmet AKGUN
  • Start date Start date
A

Ahmet AKGUN

Hi
Compiler gives error to code shown below.
It says "refering to unassigned object "rdReader" in finally block".
Is the code below a bad usage of try-finally ? How can I write this code
better without error ?
if I declare rdReader in try block, then finally block cant see this
definition.
I must be sure that Reader cursor closed, so I put it in finally.

any help ?



OleDbDataReader rdReader;
OleDbCommand dbCmd;

try
{
rdReader= dbCmd.ExecuteReader();
}
catch(..)
{
}
finally
{
rdReader.Close();
}
 
The rdReader is null because the ExecuteReader method has thrown an
exception and the rdReader is never assigned.

Just change the finally bit to:

finally
{
if( rdReader != null ) {
rdReader.Close();
}
}

so the Close is only called if the rdReader is valid.

regards

John Farrow
 
you can also try this. once the object exit the USING block, it will
automatically disposed
the object.

try
{
using (SqlCommand dbCmd = new SqlCommand())
{
//do something
using (SqlDataReader rdReader= dbCmd.ExecuteReader())
{
//do something
}
}
}
catch
{
//do something
}
 
Hi,
Initilize the variable to null when you declare it.

OleDbDataReader rdReader = null;
OleDbCommand dbCmd = null;

Cheers
Benny
 
Back
Top