How to avoid throwing an error when SQL Select returns nothing

I read somewhere that you should never use error conditions like a normal program flow. Great meaning to me ... But

C # application sitting on top of MySQL db. I need to parse a string value into two parts, id and value. (The raw data comes from the Devonian database) then check the value against the lookup table. So, a few original lines might look like this:

"6776 Purple People Eater"

"BIK Yellow Polka-Dot Bikini (currently in use)"

"DCP Deuce Coup"

So my little utility parses each row in id and description based on the index of the first space (luckily it matches). Then I pass the id to the lookup, get the new value, and leave.

Unfortunately TPTB also decided that we no longer need stinkin 'Yellow Polka-Dot Bikinis (currently in use). So BIK doesn't return a string. Here's a piece of code:

    foreach (string product in productTokens) {
      tempProduct = product.Trim();
      if (tempProduct.Length > 0) {
        if (tempProduct.Length < 10) {
          product_id = tempProduct;
        }
        else {
          int charPosition = tempProduct.IndexOf(" ");
          product_id = tempProduct.Substring(0, charPosition);
        }
        try {
          s_product = productAdapter.GetProductName(product_id).ToString();
        }
        catch (Exception e) {
          if (e.Message.ToString() == "Object reference not set to an instance of an object.") {
            s_product = "";
          }
          else {
            errLog.WriteLine("Invalid product ID " + e.Message.ToString());
            Console.WriteLine("Invalid product ID " + e.Message.ToString());
            throw;
          } //else
        } //catch
        if (s_product.Length > 0) {
          sTemp = sTemp + s_product + "; ";
        }
      } //if product.length > 0
    } //foreach product in productTokens

      

Really, really ugly! Specifically the part where I am testing for an invalid IDin in the catch block. There just has to be a better way to handle it.

If anyone can help me, I would really appreciate it.

Thank.

0


source to share


3 answers


You shouldn't call ToString () at this point, you should first check if the return value is null;



object productName = productAdapter.GetProductName(product_id);
if ( productName != null )
{
    s_product = productName.ToString();
}
else
{
    s_product = String.Empty;
}

      

+2


source


In addition to Rob and Mark's recommendations, and based on your code above, I suggest another trick; I would be very surprised if it productAdapter.GetProductName()

doesn't return already String

, in which case calling ToString () on it is redundant. If it does already return String

, then your whole try / catch block will become one line:

s_product = productAdapter.GetProductName(product_id) ?? string.Empty;

      

Also, I think it would be helpful to mention something else that already returns String

- Exception.Message

. Thus, all the different places you call ToString () in your code are overkill as well.

Also, I would suggest using an instance method String.Split()

rather than a combination of IndexOf

and SubString

:



product_id = tempProduct.Split(" ", 2)[1];

      

Finally, deciding which type Exception

you caught by examining the property Message

should be entirely the last scenario. Even if you really need to catch NullReferenceException

here, you must do it explicitly:

catch (NullReferenceException) {
    s_product = "";
}
catch (Exception e) {
    // Log your invalid ID error condition here
}

      

PS: I'm also not entirely sure if this question has anything to do with MySQL at all, since there is no proof of any DB API in your code.

+1


source


Can't you just check if GetProductName is returning null?

var productName = s_product = productAdapter.GetProductName(product_id);
if(productName == null) { ... do something }
else {
    string name = productName.ToString();
}

      

0


source







All Articles