Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Under C# how much of a performance hit is a try, throw and catch block

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#?

like image 310
Noah Avatar asked Mar 05 '09 18:03

Noah


1 Answers

It's a bad design under any language.

Exception are designed to be caught at the level which you can deal with them. Catching an exception, just to throw it again is just a pointless waste of time (it also causes you to lose valuable information about the location of the original error).

Apparently, the guy who wrote that code, used to use error codes, and then switched to exceptions without actually understanding how they work. Exceptions automatically "bubble up" the stack if there is no catch at one level.

Also, note that exceptions are for exceptional occurrences. Thing that should never happen. They should not be used in place to normal validity checking (i.e., don't catch a divide-by-zero exception; check to see if the divisor is zero beforehand).

like image 117
James Curran Avatar answered Sep 29 '22 10:09

James Curran