Let’s assume that you read in a large XML file and about 25% of the nodes are optional, so you really don’t care if they are there, however, if they are provided to you, you would still read them in and do something with them (store them in a db for example).
Since they are optional, isn’t it OK in this case to wrap them in empty try . . . catch blocks, so in the event that they are not there, the program just continues execution? You don’t care about throwing an error or anything similar.
Keep in mind that just because they are optional does not mean you don’t want to check for them. It just means that the person providing you with the XML either doesn’t want you to know certain information or they do want you to know and it is up to you to handle it.
Finally, if this was just a few nodes, it wouldn’t be a big deal, but if you have 100 nodes that are optional for example, it can be a pain to check if each one is null first or halting execution if a null was found, hence the reason why I asked if this is valid reason for empty try catch statements.
If processing node X is optional then your code should looks something like:
and not:
Now if there is no way to determine if node X exists other than to try to use it, or if it’s possible for node X to be removed after you check to see if it’s there, then you’re forced to use the try/catch model. That isn’t the situation here. (As opposed to say, checking if a file exists before reading it; someone can delete it after you check to see if it’s there.)
————————————————————
Edit:
Since it seems your issue is to access node “grandchild” alone in the following XML in which ‘Parent’ may not exist. (Please excuse my poor ability to render this XML in SO; knowledgeable readers feel free to edit in the appropriate formatting.)
For that I’d do something like this:
Then you can do: