Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to handle System.Data.SqlTypes.SqlNullValueException

I have following code:

public string getFinalCon(string desid)
        {
            string finalConId = null;
            try
            {
                query = "select finalConID from discussions where desid=@did";
                com = new SqlCommand(query, con);
                com.Parameters.AddWithValue("@did", desid);
                con.Open();
                sdr = com.ExecuteReader();
                while (sdr.Read())
                {
                    if (sdr.GetString(0).Equals("none") == false && sdr.GetString(0)!=null)
                    {
                        finalConId = sdr.GetString(0);
                        break;
                    }
                }
                con.Close();
            }
            catch (Exception)
            {
            }
            return finalConId;
        }

As you can see I am catching the "Exception", the global exception. But the problem is that whenever this line finalConId=sdr.GetString(0) is executed, the system throws System.Data.SqlTypes.SqlNullValueException. Yes it will surely throw it whenever there is NULL value in the database in the corresponding field. But what I want is that this exception should be catched by the catch block and the function should return the default value of finalConId that is NULL as declared in starting of the function. But this is not happening instead it shows up my error page. I am calling this function like this:

string conid = getFinalCon(Request["id"].ToString());

if (conid == null)
{ /*---some code---*/}
else
{/*---some code---*}

Please anyone tell me how to handle this exception.

like image 603
Shiva Pareek Avatar asked Nov 27 '12 07:11

Shiva Pareek


2 Answers

Don't catch exceptions when you don't need to. The proper way to do this is to test sdr.IsDBNull(0) before calling sdr.GetString(0). If IsDBNull() returns true, then GetString() will throw an exception and you should not call it.

It's also very poor practice to swallow all exceptions without indicating some sort of error. catch { } or catch (Exception) { } should be avoided in almost all cases. If something catastrophic happens (the DB connection goes down, for example) you want to allow that exception to propagate. Otherwise, how is the caller to distinguish between the cases "null value in that column" and "database connection died?"

like image 126
cdhowie Avatar answered Sep 23 '22 05:09

cdhowie


its better to check value with DBNull.Value or IsDBNull() like this

if (reader.IsDBNull(0) && sdr.GetString(0).Equals("none") == false)
          //sdr.GetString(0)!=DBNull.Value)

if you want return null when exception than do like this

string conid;
try
{
  conid = getFinalCon(Request["id"].ToString());
}
Catch(Exception ex)
{
  conid =null;
}
like image 37
Pranay Rana Avatar answered Sep 25 '22 05:09

Pranay Rana