Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the real overhead of try/catch in C#?

So, I know that try/catch does add some overhead and therefore isn't a good way of controlling process flow, but where does this overhead come from and what is it's actual impact?

like image 682
JC Grubbs Avatar asked Sep 09 '08 16:09

JC Grubbs


People also ask

Does try catch have overhead?

There has to be an overhead for try/catch blocks so that the CLR can handle the exceptions. C# runs on the . NET CLR(a virtual machine).

What is try catch in C?

The try-except statement is a Microsoft extension to the C language that enables applications to gain control of a program when events that normally terminate execution occur. Such events are called exceptions, and the mechanism that deals with exceptions is called structured exception handling.

Is try catch costly?

Using try catch adds performance cost, but it isn't a major performance cost. Isn't it best to use try catch block as much as possible? No, it is best to use try catch block when makes sense. The performance cost depends on which compiler you use.

What is try catch in C sharp?

The try-catch statement consists of a try block followed by one or more catch clauses, which specify handlers for different exceptions. When an exception is thrown, the common language runtime (CLR) looks for the catch statement that handles this exception.


1 Answers

Three points to make here:

  • Firstly, there is little or NO performance penalty in actually having try-catch blocks in your code. This should not be a consideration when trying to avoid having them in your application. The performance hit only comes into play when an exception is thrown.

  • When an exception is thrown in addition to the stack unwinding operations etc that take place which others have mentioned you should be aware that a whole bunch of runtime/reflection related stuff happens in order to populate the members of the exception class such as the stack trace object and the various type members etc.

  • I believe that this is one of the reasons why the general advice if you are going to rethrow the exception is to just throw; rather than throw the exception again or construct a new one as in those cases all of that stack information is regathered whereas in the simple throw it is all preserved.

like image 172
Shaun Austin Avatar answered Sep 20 '22 15:09

Shaun Austin