XmlNode.SelectSingleNode exception

  • Thread starter Thread starter Jesper
  • Start date Start date
J

Jesper

Hi,

I've read somewhere that try/catch shoudn't be used as an
alternative to if clauses (maybe it was in C++ regi).
However, when using XmlNode.SelectSingleNode(XPath
expression) to get a node, it throws an exception instead
of returning null if the node doesn't excist. I'm a bit
tentative to use a catch statement to handle this as this
is not in my program considered a severe error. Is my
conception of try/catch in C# wrong in relation to C++
or/and is there a way of query for the excistence of a
particular node in a Xml document without using catch if
the node isn't present in the document.

Best regards Jesper.
 
Jesper said:
Hi,

I've read somewhere that try/catch shoudn't be used as an
alternative to if clauses (maybe it was in C++ regi).
However, when using XmlNode.SelectSingleNode(XPath
expression) to get a node, it throws an exception instead
of returning null if the node doesn't excist. I'm a bit
tentative to use a catch statement to handle this as this
is not in my program considered a severe error. Is my
conception of try/catch in C# wrong in relation to C++
or/and is there a way of query for the excistence of a
particular node in a Xml document without using catch if
the node isn't present in the document.
I think you are mistaken about the behavior of XmlNode.SelectSingleNode. It
returns null if a valid xpath query returns an empty NodeList. It only
throws an exception if, for instance, your xpath query is invalid.

But to your question: Catching exceptions is much slower than evaluating
return codes, and so best practices discourage catching exceptions for
things that will happen all the time. If the exception will only be thrown
occasionally, then it's ok.

David
 
Back
Top