I have read in an article that writing many try catch exception block in code will add performance overhead.
Is that true ?Why is it declaring many exception block affect the performance?
Thanks SCA
I have read in an article that writing many try catch exception block in code will add performance overhead.
Is that true ?Why is it declaring many exception block affect the performance?
Thanks SCA
Try/catch blocks do not incur much performance overhead.
Throwing exceptions does have some overhead, but that should not be an issue - exceptions are supposed to be exceptional.
This article goes into a bit more detail on how try/catch blocks are implemented and their runtime cost: http://www.programmersheaven.com/user/pheaven/blog/175-Do-trycatch-blocks-hurt-runtime-performance/
I think the following quote sums up exceptions nicely
If you're worried about exception performance you're using them wrong
Exceptions won't have a significant performance impact on your application if you use them as they were intended to be use. That is for exceptional situations.
There is a lot of bad information out there about exception performance. It would be great if you could post a link to the article you were reading so we can see why they think it will be a problem. It may be they are covering one corner case aspect that is not applicable to most situations.
(I apologize for not directly answering your question)
Try/Catch exception blocks are recommended in places where you want to catch potentially, but rare, failed or abnormal behavior such as reading a file or querying a database. You may also want to put try/catch blocks where a function is unable to fulfill it's contract.
Use assertions to catch bugs or defects that should never occur. Also use assertions as self documenting code. (See Defensive Programming chapter in Code Complete 2nd Edition).
Here's a good article regarding exception overhead from the creator of TheDailyWTF:
http://weblogs.asp.net/alex_papadimoulis/archive/2005/03/29/396141.aspx
A brief example taken from the article throwing 1000 exceptions:
Console.WriteLine(Now().ToString("hh:mm:ss.fffffff"))
DoNothingImportant()
ThrowRecursiveExceptions(1000)
Console.WriteLine(Now().ToString("hh:mm:ss.fffffff"))
Output:
10:57:38.0252702
10:58:39.9205680
You can see it takes about 2 minutes for this, but since they're only supposed to be used for exceptional behavior, I wouldn't worry about it. Besides, an exception that truly is "an exception" which is discovered through the use of catching and logging is going to be worth infinitely more to you when you can fix it right away as opposed to trying ghost debug the problem when it fails silently.