[...]
Question is, from a performance, memory usage point of view, is there
harm in including all those statements inside the try/catch?
Both of your examples have the same number of try/catch blocks. So even
if each try/catch block reduced performance, both of those two examples
would perform the same.
More to the point, I will pick correct code over fast code any day. If
the thing you are calling might throw an exception that you need to
handle, you need a try/catch block. Even if it slows your code down.
Note: try/catch blocks that simply eat exceptions are bad. Don't do
that, except possibly at the highest level of your program for the
purpose of error-reporting, and then only if you know for sure that an
exception cannot have destabilized your program (keeping in mind that
some exceptions, such as OutOfMemoryException, might be unrecoverable).
If you are designing the entire hierarchy of code and so have complete
control over how errors are handled, then you may still wonder whether
try/catch is better than returning error values. But the only way to
answer that is to measure performance and see if it matters in your
scenario.
That said, intuitively it's likely to be a wash. One of the advantages
of exceptions is that error handling needs to be present only at the
site where the error can in fact be dealt with. It allows all the code
in between to not have to worry about it.
So, not only can the code itself be simpler, you also don't have to
chain return values that would otherwise be needed in order to propagate
errors back to the level where the error will actually be handled.
Checking, storing, and returning all those return codes can itself be
overhead.
From a performance point of view, either approach is unlikely to have
any real effect on how fast your code runs. But if you're in a situation
where it matters, the only correct way to decide is to measure the
actual performance and see for yourself.
Probably one of the strongest arguments in favor of using exceptions is
that the entire .NET API is designed around them. You can avoid them in
your own code, but you can't avoid dealing with them altogether, and
your own code will seem out-of-place if it's not using exceptions for
error handling.
Pete