In a method, I want to be able to insert a value into a div which is part of the html document I choose to parse.
public void AddToDiv(string div) { //Code to read the html document and look for the div //(name specified as the parameter of this method). }
Question is, I could specify a div called ‘abc’ but the html document may not have this div. Fair enough, but what is the difference between me saying:
try { //Method logic to parse document for the div } catch(ArgumentException ex) { // (I wouldn't supress this catch block in production code, // just omitting body details for simplicity. }
OR
public void ParseDocument { //Logic here... if(!document.Contains(div) { throw new ArgumentException(); } }
In short, what is the difference between a catch block and saying throw new [ExceptionType here] in the main logic block? How do I decide which is to use?
Thanks
Personally, I’d check for existence, rather than allowing the exception to be thrown, it’s easier to determine the flow of logic, and fits better with the intent of your code.
See these questions and answers for a broader discussion
When to throw an exception
Is there any valid reason to ever ignore a caught exception
How slow are .net exceptions?
EDIT:
On second thoughts, you should consider the expense of the ‘containts’ check. If it’s likely to be as expensive as actually getting the div, and it’s doubling the time it takes the routine to run and if this lag degrades performance to the point where it’ll be noticed, then possibly it’s better to just go and get the div. I’d still catch it and throw the ArgumentException, with the original exception as the inner exception.
NB: Don’t optimise unless you need to.