1

The .Replace() is causing the exception because authorElement.QuerySelector(...).InnerTextClean is returning null. This is very rare (1/100,000) so I would rather use try catch than check for null.

author.salescount = Convert.ToInt32(authorElement.QuerySelector("div.sale-info.is-hidden-phone > em").InnerTextClean.Replace(",", ""));

So my question is, do I have to break this up into many lines and only try catch the individual function that fails?

.ToInt32() obviously cant accept a null, but I would assume the try catch block will throw the exception as soon as it occurs. So then I could wrap the entire thing.

I guess I solved it, am I wrong and/or is there something I haven't considered?

ThomasRones
  • 657
  • 8
  • 29
  • 4
    `I would rather use try catch than check for null.` That is the wrong decision. Use `int.TryParse`. – mjwills Dec 07 '18 at 12:04
  • Perfect, that's why I posted this. – ThomasRones Dec 07 '18 at 12:05
  • Checking for null is better than handling NullReferenceException... Check the output of `authorElement.QuerySelector` for null before trying to convert it to integer. – Chetan Dec 07 '18 at 12:06
  • 1
    Possible duplicate of [What's the main difference between int.Parse() and Convert.ToInt32](https://stackoverflow.com/questions/199470/whats-the-main-difference-between-int-parse-and-convert-toint32) – mjwills Dec 07 '18 at 12:06
  • According to MSDN : Check for error conditions in code if the event happens routinely and could be considered part of normal execution. When you check for common error conditions, less code is executed because you avoid exceptions. https://learn.microsoft.com/en-us/dotnet/standard/exceptions/best-practices-for-exceptions – ThomasRones Dec 07 '18 at 12:07
  • From the same article. `For conditions that are likely to occur but might trigger an exception, consider handling them in a way that will avoid the exception` Which seems pertinent to your situation. :) In terms of proving to you that the approach I am suggesting is superior to yours - I can't. I mean, mine is likely easier to read and may perform faster. But, if you want to do it your way no-one is going to stop you. – mjwills Dec 07 '18 at 12:11
  • Ahh ok, I understand now. It would be interesting to see what actually happens when a try catch is executed -- like memory flows and in whatever language C# is written in (C++?)... maybe I'll do some research and make another question. – ThomasRones Dec 07 '18 at 12:15

1 Answers1

0

I would handle the null case instead of try/catch

string inner = authorElement.QuerySelector("div.sale-info.is-hidden-phone > em")?.InnerTextClean?.Replace(",", "");
int temp;
author.salescount = int.TryParse(inner, out temp) ? temp : -1; // -1 in case of null
fubo
  • 44,811
  • 17
  • 103
  • 137