2

So I took over this project and one page is throwing a lot of errors. I would need to refactor the whole thing but as always time is an issue.

In one case the code check's whether a datareader has any rows and if not go to an error page. However as the code is now the datareader can be null (didn't successfully connect to db) and in those cases I can't use

if (!dr.HasRows)
//

becasuse it obviously gives me 'nullreferenceexception was unhandled by code'. I tried with !dr.Read but same thing.

A part of the code is something like

SqlDataReader dr = null;
try
{
//connect to db etc
dr = DbHelper.GetReader("sp_GetCustomer", param);
}
catch
{
//show an error message
}

// and then:
if (!dr.HasRows)
{

}

Any suggestions?

Thanks in advance.

5
  • How about putting the dr.hasrows in the try as well and handle that error as well? Commented Apr 5, 2011 at 13:10
  • 1
    @Elad: NO! Avoid obvious exceptions, don't catch them. Commented Apr 5, 2011 at 13:14
  • @Dan Puzey - Sure, but stuff happens. You can never know, and if the specific stuff happens, I would rather catch it than not... Give some kind of inteligent error. Commented Apr 5, 2011 at 13:16
  • @Elad: you can always avoid catching NullReferenceException by checking the thing you're about to reference. Commented Apr 5, 2011 at 13:20
  • @Dan Puzey - Ohh... Now I see what your saying. They your right. Commented Apr 5, 2011 at 13:22

2 Answers 2

9

What about:

if (dr == null || !dr.HasRows) {
    // Do something
}
Sign up to request clarification or add additional context in comments.

4 Comments

I think that would evaluate !dr.HasRows as well anyway, no?
of course, I am getting too tired dealing with this mess. Thanks
@Elad: No, in C# additional parameters for the if statement are only checked as necessary. This is referred to as "short-circuited". You can read more here.
If dr==null is true, it will short circuit the evaluation - OR operator has no need to evaluate the right hand side of the expression if it knows the left hand side is true.
2

One possibility is:

SqlDataReader dr = null;
try
{
    //connect to db etc
    dr = DbHelper.GetReader("sp_GetCustomer", param);
    if (!dr.HasRows)
    {

    }
}
catch
{
//show an error message
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.