Can you mimic 'Resume Next' in C#?

  • Thread starter Thread starter Dave
  • Start date Start date
D

Dave

Hi,

I have a C# program that is parsing an XML file and
loading a database table. Some of the elements may be
missing but I want to continue with loading the data
anyway because they may not be applicable.

So, if '190' doesn't exist using the following code:

doc.SelectSingleNode("descendant::companyinfo
[@a:sourceid='190']/sourcekey/id", nsmgr).InnerText

will raise:

"Object reference not set to an instance of an object."

I just want to continue processing subsequent nodes. How
can I mimic the resume next in VB. Can you test for
certain exceptions and decide to continue.

Thanks Dave
 
There is no equivalent.

You could put a try/catch around every statement, but that has 2
implications:
1) Your code will be littered with try/catch blocks and hard to read - not
to mention much longer
2) Catching/processing exceptions is a costly thing. If half your nodes are
missing, and you are throwin/catching dozens/hundreds of exceptions, your
code would run noticeably slower.

Your best bet is to code in such a way as to avoid exceptions being raised
in the first place. The way you would prefer to have is just lazy coding -
the most efficient way is to just avoid having these exceptions thrown in
the first place.

Test the result of SelectSingleNode to make sure it is not null, and only
then proceed with whatever else you were going to do.
 
"Object reference not set to an instance of an object."

You just need to break it into two statements:

XmlNode node =
doc.SelectSingleNode("descendant::companyinfo[@a:sourceid='190']/sourcekey/i
d", nsmgr)
string value;

if (node != null)
value = node.InnerText;

HTH,
Eric Cadwell
http://www.origincontrols.com
 
Behind the scenes, all Resume Next does is wrap every single statement in a
try catch block. If you are a VB programmer, take one of your programs that
used Resume Next and look at the IL. It's awful that VB.NET lets you use it
all, and it should be avoided at all cost.

Not every line needs a wrapper so it makes no sense to use Resume next
nowadays. Instead, wrap the lines that you know are risky and trap specific
exceptions. It's more verbose for sure, but it's infitinetely better as a
methodology.

HTH,

Bill
 
Back
Top