HtmlAgilityPack Error Handling - catching exception

c# error-handling html-agility-pack

Question

I'm trying to determine how to catch the exception what i am getting is Object reference not set to an instance of an object.

is there any better way to catch the exception and showed to the user cause of the exception?

       baseUrl = "my url....";
        try
        {
            HtmlWeb hw = new HtmlWeb();
            HtmlDocument docSRC = hw.Load(baseUrl);

            //if (docSRC.DocumentNode.SelectNodes("//img/@src").Count > 0)
            //{

            //}

            foreach (HtmlNode link in docSRC.DocumentNode.SelectNodes("//img/@src"))
            {
                HtmlAttribute att = link.Attributes["src"];
                srcTags.Add(att.Value);

            }
        }
        catch (Exception ex)
        {
            //catch reason for exception....
        }

Popular Answer

I can't think of any other way to handle exception. But it will be better if you can avoid the exception in the first place.

Looking at code snippet posted, NullReferenceException could be thrown when there is a link that doesn't have src attribute (this part att.Value will throw exception because att is null in this case).

You can use GetAttributeValue() method to avoid the exception, for example :

//here when the attribute not found, the 2nd parameter will be returned 
//(empty string in this case)
var src =  link.GetAttributeValue("src", "");


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why