First of all, a disclaimer: I have experience in other languages, but am still learning the subtleties of C#
On to the problem… I am looking at some code, which uses the try/catch blocks in a way that concerns me. When a parsing routine is called, rather than return an error code, the programmer used the following logic
catch (TclException e) { throw new TclRuntimeError('unexpected TclException: ' + e.Message,e); }
This is caught by the caller, which throws the same error …
… which is caught by the caller, which throws the same error …
….. which is caught by the caller, which throws the same error …
back up about 6 levels.
Am I right in thinking all these catch/throw blocks are causing a performance problem, or is this a reasonable implementation under C#?
Throw (rather than catch) is expensive.
Don’t put a catch block in unless you are going to do something useful (i.e. convert to a more useful exception, handle the error).
Just rethrowing the exception (throw statement without argument) or, even worse, throw the same object as just caught is definitely the wrong thing.
EDIT: To avoid ambiguity:
Rethrow:
Create exception from previous exception object, where all the runtime provided state (notably stack trace) is overwritten:
The latter case is a pointless way to throw away information about the exception. and without anything preceding the throw in the catch block is doubly pointless. It can be worse:
which loses almost all the useful state information e contained (including what was originally thrown.)