<p>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 its actual impact?</p>

[{'answer_id': 52322, 'author': 'Mike Stone', 'author_id': 122, 'author_profile': 'https://Stackoverflow.com/users/122', 'pm_score': 7, 'selected': True, 'text': "<p>I'm not an expert in language implementations (so take this with a grain of salt), but I think one of the biggest costs is unwinding the stack and storing it for the stack trace.  I suspect this happens only when the exception is thrown (but I don't know), and if so, this would be decently sized hidden cost every time an exception is thrown... so it's not like you are just jumping from one place in the code to another, there is a lot going on.</p>\n\n<p>I don't think it's a problem as long as you are using exceptions for EXCEPTIONAL behavior (so not your typical, expected path through the program).</p>\n"}, {'answer_id': 52330, 'author': 'Tobi', 'author_id': 5422, 'author_profile': 'https://Stackoverflow.com/users/5422', 'pm_score': 3, 'selected': False, 'text': "<p>In my experience the biggest overhead is in actually throwing an exception and handling it. I once worked on a project where code similar to the following was used to check if someone had a right to edit some object. This HasRight() method was used everywhere in the presentation layer, and was often called for 100s of objects.</p>\n\n<pre><code>bool HasRight(string rightName, DomainObject obj) {\n  try {\n    CheckRight(rightName, obj);\n    return true;\n  }\n  catch (Exception ex) {\n    return false;\n  }\n}\n\nvoid CheckRight(string rightName, DomainObject obj) {\n  if (!_user.Rights.Contains(rightName))\n    throw new Exception();\n}\n</code></pre>\n\n<p>When the test database got fuller with test data, this lead to a very visible slowdown while openening new forms etc.</p>\n\n<p>So I refactored it to the following, which - according to later quick 'n dirty measurements - is about 2 orders of magnitude faster:</p>\n\n<pre><code>bool HasRight(string rightName, DomainObject obj) {\n  return _user.Rights.Contains(rightName);\n}\n\nvoid CheckRight(string rightName, DomainObject obj) {\n  if (!HasRight(rightName, obj))\n    throw new Exception();\n}\n</code></pre>\n\n<p>So in short, using exceptions in normal process flow is about two orders of magnitude slower then using similar process flow without exceptions.</p>\n"}, {'answer_id': 52352, 'author': 'Hafthor', 'author_id': 4489, 'author_profile': 'https://Stackoverflow.com/users/4489', 'pm_score': 2, 'selected': False, 'text': '<p>I made a <a href="http://freachable.net/2007/11/10/TryAssertTryBlocksExpensiveCatchExceptionExAssumptionreset.aspx" rel="nofollow noreferrer">blog entry</a> about this subject last year.\nCheck it out. Bottom line is that there is almost no cost for a try block if no exception occurs - and on my laptop, an exception was about 36&mu;s. That might be less than you expected, but keep in mind that those results where on a shallow stack. Also, first exceptions are really slow.</p>\n'}, {'answer_id': 52390, 'author': 'Shaun Austin', 'author_id': 1120, 'author_profile': 'https://Stackoverflow.com/users/1120', 'pm_score': 7, 'selected': False, 'text': '<p>Three points to make here:</p>\n\n<ul>\n<li><p>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.</p></li>\n<li><p>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. </p></li>\n<li><p>I believe that this is one of the reasons why the general advice if you are going to rethrow the exception is to just <code>throw;</code> 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.</p></li>\n</ul>\n'}, {'answer_id': 59645, 'author': 'dotmad', 'author_id': 6060, 'author_profile': 'https://Stackoverflow.com/users/6060', 'pm_score': 2, 'selected': False, 'text': "<p>Not to mention if it's inside a frequently-called method it may affect the overall behavior of the application.    <br>\nFor example, I consider the use of Int32.Parse as a bad practice in most cases since it throws exceptions for something that can be caught easily otherwise.</p>\n\n<p>So to conclude everything written here:     <br>\n1) Use try..catch blocks to catch unexpected errors - almost no performance penalty.   <br>\n2) Don't use exceptions for excepted errors if you can avoid it.</p>\n"}, {'answer_id': 108400, 'author': 'HTTP 410', 'author_id': 13118, 'author_profile': 'https://Stackoverflow.com/users/13118', 'pm_score': 5, 'selected': False, 'text': '<p>Are you asking about the overhead of using try/catch/finally when exceptions aren\'t thrown, or the overhead of using exceptions to control process flow? The latter is somewhat akin to using a stick of dynamite to light a toddler\'s birthday candle, and the associated overhead falls into the following areas:</p>\n\n<ul>\n<li>You can expect additional cache misses due to the thrown exception accessing resident data not normally in the cache.</li>\n<li><p>You can expect additional page faults due to the thrown exception accessing non-resident code and data not normally in your application\'s working set.</p>\n\n<ul>\n<li>for example, throwing the exception will require the CLR to find the location of the finally and catch blocks based on the current IP and the return IP of every frame until the exception is handled plus the filter block.</li>\n<li>additional construction cost and name resolution in order to create the frames for diagnostic purposes, including reading of metadata etc.</li>\n<li><p>both of the above items typically access "cold" code and data, so hard page faults are probable if you have memory pressure at all:</p>\n\n<ul>\n<li>the CLR tries to put code and data that is used infrequently far from data that is used frequently to improve locality, so this works against you because you\'re forcing the cold to be hot.</li>\n<li>the cost of the hard page faults, if any, will dwarf everything else.</li>\n</ul></li>\n</ul></li>\n<li>Typical catch situations are often deep, therefore the above effects would tend to be magnified (increasing the likelihood of page faults).</li>\n</ul>\n\n<p>As for the actual impact of the cost, this can vary a lot depending on what else is going on in your code at the time. Jon Skeet has a <a href="https://jonskeet.uk/csharp/exceptions2.html" rel="nofollow noreferrer">good summary here</a>, with some useful links. I tend to agree with his statement that if you get to the point where exceptions are significantly hurting your performance, you have problems in terms of your use of exceptions beyond just the performance.</p>\n'}, {'answer_id': 227544, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 2, 'selected': False, 'text': "<p>It is vastly easier to write, debug, and maintain code that is free of compiler error messages, code-analysis warning messages, and routine accepted exceptions (particularly exceptions that are thrown in one place and accepted in another). Because it is easier, the code will on average be better written and less buggy.</p>\n\n<p>To me, that programmer and quality overhead is the primary argument against using try-catch for process flow.</p>\n\n<p>The computer overhead of exceptions is insignificant in comparison, and usually tiny in terms of the application's ability to meet real-world performance requirements.</p>\n"}, {'answer_id': 580510, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 1, 'selected': False, 'text': '<p>I really like Hafthor\'s <a href="http://freachable.net/2007/11/10/TryAssertTryBlocksExpensiveCatchExceptionExAssumptionreset.aspx" rel="nofollow noreferrer">blog post</a>, and to add my two cents to this discussion, I\'d like to say that, it\'s always been easy for me to have the DATA LAYER throw only one type of exception (DataAccessException). This way my BUSINESS LAYER knows what exception to expect and catches it. Then depending on further business rules (i.e. if my business object participates in the workflow etc), I may throw a new exception (BusinessObjectException) or proceed without re/throwing. </p>\n\n<p>I\'d say don\'t hesitate to use try..catch whenever it is necessary and use it wisely!</p>\n\n<p>For example, this method participates in a workflow... </p>\n\n<p>Comments?</p>\n\n<pre><code>public bool DeleteGallery(int id)\n{\n    try\n    {\n        using (var transaction = new DbTransactionManager())\n        {\n            try\n            {\n                transaction.BeginTransaction();\n\n                _galleryRepository.DeleteGallery(id, transaction);\n                _galleryRepository.DeletePictures(id, transaction);\n\n                FileManager.DeleteAll(id);\n\n                transaction.Commit();\n            }\n            catch (DataAccessException ex)\n            {\n                Logger.Log(ex);\n                transaction.Rollback();                        \n                throw new BusinessObjectException("Cannot delete gallery. Ensure business rules and try again.", ex);\n            }\n        }\n    }\n    catch (DbTransactionException ex)\n    {\n        Logger.Log(ex);\n        throw new BusinessObjectException("Cannot delete gallery.", ex);\n    }\n    return true;\n}\n</code></pre>\n'}, {'answer_id': 624610, 'author': 'BlackWasp', 'author_id': 21862, 'author_profile': 'https://Stackoverflow.com/users/21862', 'pm_score': 2, 'selected': False, 'text': '<p>I wrote an article about this a while back because there were a lot of people asking about this at the time. You can find it and the test code at <a href="http://www.blackwasp.co.uk/SpeedTestTryCatch.aspx" rel="nofollow noreferrer">http://www.blackwasp.co.uk/SpeedTestTryCatch.aspx</a>.</p>\n\n<p>The upshot is that there is a tiny amount of overhead for a try/catch block but so small that it should be ignored. However, if you are running try/catch blocks in loops that are executed millions of times, you may want to consider moving the block to outside of the loop if possible.</p>\n\n<p>The key performance issue with try/catch blocks is when you actually catch an exception. This can add a noticeable delay to your application. Of course, when things are going wrong, most developers (and a lot of users) recognise the pause as an exception that is about to happen! The key here is not to use exception handling for normal operations. As the name suggests, they are exceptional and you should do everything you can to avoid them being thrown. You should not use them as part of the expected flow of a program that is functioning correctly.</p>\n'}, {'answer_id': 2080967, 'author': 'Vando', 'author_id': 220904, 'author_profile': 'https://Stackoverflow.com/users/220904', 'pm_score': 1, 'selected': False, 'text': '<p>We can read in Programming Languages Pragmatics by Michael L. Scott that the nowadays compilers do not add any overhead in common case, this means, when no exceptions occurs. So every work is made in compile time. \nBut when an exception is thrown in run-time, compiler needs to perform a binary search to find the correct exception and this will happen for every new throw that you made. </p>\n\n<p>But exceptions are exceptions and this cost is perfectly acceptable. If you try to do Exception Handling without exceptions and use return error codes instead, probably you will need a if statement for every subroutine and this will incur in a really real time overhead. You know a if statement is converted to a few assembly instructions, that will performed every time you enter in your sub-routines.</p>\n\n<p>Sorry about my English, hope that it helps you. This information is based on cited book, for more information refer to Chapter 8.5 Exception Handling.</p>\n'}, {'answer_id': 2765798, 'author': 'Sebastian Ramadan', 'author_id': 332409, 'author_profile': 'https://Stackoverflow.com/users/332409', 'pm_score': -1, 'selected': False, 'text': '<p>Let us analyse one of the biggest possible costs of a try/catch block when used where it shouldn\'t need to be used:</p>\n\n<pre><code>int x;\ntry {\n    x = int.Parse("1234");\n}\ncatch {\n    return;\n}\n// some more code here...\n</code></pre>\n\n<p>And here\'s the one without try/catch:</p>\n\n<pre><code>int x;\nif (int.TryParse("1234", out x) == false) {\n    return;\n}\n// some more code here\n</code></pre>\n\n<p>Not counting the insignificant white-space, one might notice that these two equivelant pieces of code are almost exactly the same length in bytes. The latter contains 4 bytes less indentation. Is that a bad thing?</p>\n\n<p>To add insult to injury, a student decides to loop while the input can be parsed as an int. The solution without try/catch might be something like:</p>\n\n<pre><code>while (int.TryParse(...))\n{\n    ...\n}\n</code></pre>\n\n<p>But how does this look when using try/catch?</p>\n\n<pre><code>try {\n    for (;;)\n    {\n        x = int.Parse(...);\n        ...\n    }\n}\ncatch\n{\n    ...\n}\n</code></pre>\n\n<p>Try/catch blocks are magical ways of wasting indentation, and we still don\'t even know the reason it failed! Imagine how the person doing debugging feels, when code continues to execute past a serious logical flaw, rather than halting with a nice obvious exception error. Try/catch blocks are a lazy man\'s data validation/sanitation.</p>\n\n<p>One of the smaller costs is that try/catch blocks do indeed disable certain optimizations: <a href="http://msmvps.com/blogs/peterritchie/archive/2007/06/22/performance-implications-of-try-catch-finally.aspx" rel="nofollow noreferrer">http://msmvps.com/blogs/peterritchie/archive/2007/06/22/performance-implications-of-try-catch-finally.aspx</a>. I guess that\'s a positive point too. It can be used to disable optimizations that might otherwise cripple safe, sane message passing algorithms for multithreaded applications, and to catch possible race conditions ;) That\'s about the only scenario I can think of to use try/catch. Even that has alternatives.</p>\n'}, {'answer_id': 45701327, 'author': 'autistic', 'author_id': 1989425, 'author_profile': 'https://Stackoverflow.com/users/1989425', 'pm_score': 3, 'selected': False, 'text': '<p>Contrary to theories commonly accepted, <code>try</code>/<code>catch</code> can have significant performance implications, and that\'s whether an exception is thrown or not!</p>\n\n<ol>\n<li><strong>It disables some automatic optimisations (by design)</strong>, and in some cases injects <em>debugging</em> code, as you can expect from a <em>debugging aid</em>. There will always be people who disagree with me on this point, but the language requires it and the disassembly shows it so those people are by dictionary definition <a href="https://www.google.com/search?q=define%3A+delusional" rel="noreferrer">delusional</a>.</li>\n<li><strong>It can impact negatively upon maintenance.</strong> This is actually the most significant issue here, but since my last answer (which focused almost entirely on it) was deleted, I\'ll try to focus on the less significant issue (the micro-optimisation) as opposed to the more significant issue (the macro-optimisation).</li>\n</ol>\n\n<hr>\n\n<p>The former has been covered in a couple of blog posts by Microsoft MVPs over the years, and I trust you could find them easily yet StackOverflow cares <em>so much</em> about <em>content</em> so I\'ll provide links to some of them as <strike>filler</strike> evidence:</p>\n\n<ul>\n<li><a href="https://blogs.msmvps.com/peterritchie/2007/06/22/performance-implications-of-try-catch-finally/" rel="noreferrer"><strong>Performance implications of <code>try</code>/<code>catch</code>/<code>finally</code></strong></a> (<a href="https://blogs.msmvps.com/peterritchie/2007/07/12/performance-implications-of-try-catch-finally-part-two/" rel="noreferrer">and part two</a>), by Peter Ritchie explores the optimisations which <code>try</code>/<code>catch</code>/<code>finally</code> disables (and I\'ll go further into this with quotes from the standard)</li>\n<li><a href="https://blogs.msdn.microsoft.com/ianhu/2005/12/19/performance-profiling-parse-vs-tryparse-vs-convertto/" rel="noreferrer"><strong>Performance Profiling <code>Parse</code> vs. <code>TryParse</code> vs. <code>ConvertTo</code></strong></a> by Ian Huff states blatantly that "exception handling is very slow" and demonstrates this point by pitting <code>Int.Parse</code> and <code>Int.TryParse</code> against each other... To anyone who insists that <code>TryParse</code> uses <code>try</code>/<code>catch</code> behind the scenes, this ought to shed some light!</li>\n</ul>\n\n<p>There\'s also <a href="https://stackoverflow.com/a/1352364/1989425">this answer</a> which shows the difference between disassembled code with- and without using <code>try</code>/<code>catch</code>.</p>\n\n<p>It seems so obvious that there <em>is</em> an overhead which is blatantly observable in code generation, and that overhead even seems to be acknowledged by people who Microsoft value! Yet I am, <em>repeating the internet</em>...</p>\n\n<p>Yes, there are dozens of extra MSIL instructions for one trivial line of code, and that doesn\'t even cover the disabled optimisations so technically it\'s a micro-optimisation.</p>\n\n<hr>\n\n<p>I posted an answer years ago which got deleted as it focused on the productivity of programmers (the macro-optimisation).</p>\n\n<p>This is unfortunate as no saving of a few nanoseconds here and there of CPU time is likely to make up for many accumulated hours of manual optimisation by humans. Which does your boss pay more for: an hour of your time, or an hour with the computer running? At what point do we pull the plug and admit that it\'s time to just <em>buy a faster computer</em>?</p>\n\n<p>Clearly, we should be <em>optimising our priorities</em>, not just our code! In my last answer I drew upon the differences between two snippets of code.</p>\n\n<p>Using <code>try</code>/<code>catch</code>:</p>\n\n<pre><code>int x;\ntry {\n    x = int.Parse("1234");\n}\ncatch {\n    return;\n}\n// some more code here...\n</code></pre>\n\n<p>Not using <code>try</code>/<code>catch</code>:</p>\n\n<pre><code>int x;\nif (int.TryParse("1234", out x) == false) {\n    return;\n}\n// some more code here\n</code></pre>\n\n<p>Consider from the perspective of a maintenance developer, which is more likely to waste your time, if not in profiling/optimisation (covered above) which likely wouldn\'t even be necessary if it weren\'t for the <code>try</code>/<code>catch</code> problem, then in scrolling through source code... One of those has four extra lines of boilerplate garbage!</p>\n\n<p>As more and more fields are introduced into a class, all of this boilerplate garbage accumulates (both in source and disassembled code) well beyond reasonable levels. Four extra lines per field, and they\'re always the same lines... Were we not taught to avoid repeating ourselves? I suppose we could hide the <code>try</code>/<code>catch</code> behind some home-brewed abstraction, but... then we might as well just avoid exceptions (i.e. use <code>Int.TryParse</code>).</p>\n\n<p>This isn\'t even a complex example; I\'ve seen attempts at instantiating new classes in <code>try</code>/<code>catch</code>. Consider that all of the code inside of the constructor might then be disqualified from certain optimisations that would otherwise be automatically applied by the compiler. What better way to give rise to the theory that <em>the compiler is slow</em>, as opposed to <em>the compiler is doing exactly what it\'s told to do</em>?</p>\n\n<p>Assuming an exception is thrown by said constructor, and some bug is triggered as a result, the poor maintenance developer then has to track it down. That might not be such an easy task, as unlike the spaghetti code of the <em>goto</em> nightmare, <code>try</code>/<code>catch</code> can cause messes in <em>three dimensions</em>, as it could move up the stack into not just other parts of the same method, but also other classes and methods, all of which will be observed by the maintenance developer, <em>the hard way</em>! Yet we are told that "goto is dangerous", heh!</p>\n\n<p>At the end I mention, <code>try</code>/<code>catch</code> has its benefit which is, <em>it\'s designed to disable optimisations</em>! It is, if you will, a <em>debugging aid</em>! That\'s what it was designed for and it\'s what it should be used as...</p>\n\n<blockquote>\n  <p>I guess that\'s a positive point too. It can be used to disable optimizations that might otherwise cripple safe, sane message passing algorithms for multithreaded applications, and to catch possible race conditions ;) That\'s about the only scenario I can think of to use try/catch. Even that has alternatives.</p>\n</blockquote>\n\n<hr>\n\n<p><strong>What optimisations do <code>try</code>, <code>catch</code> and <code>finally</code> disable?</strong></p>\n\n<p>A.K.A</p>\n\n<p><strong>How are <code>try</code>, <code>catch</code> and <code>finally</code> useful as debugging aids?</strong></p>\n\n<p>they\'re write-barriers. This comes from the standard:</p>\n\n<p>12.3.3.13 Try-catch statements </p>\n\n<blockquote>\n  <p>For a statement <em>stmt</em> of the form:</p>\n\n<pre><code>try try-block\ncatch ( ... ) catch-block-1\n... \ncatch ( ... ) catch-block-n\n</code></pre>\n  \n  <ul>\n  <li>The definite assignment state of <em>v</em> at the beginning of <em>try-block</em> is the same as the definite assignment state of <em>v</em> at the beginning of <em>stmt</em>.</li>\n  <li>The definite assignment state of <em>v</em> at the beginning of <em>catch-block-i</em> (for any <em>i</em>) is the same as the definite assignment state of <em>v</em> at the beginning of <em>stmt</em>. </li>\n  <li>The definite assignment state of <em>v</em> at the end-point of <em>stmt</em> is definitely assigned if (and only if) <em>v</em> is definitely assigned at the end-point of <em>try-block</em> and every <em>catch-block-i</em> (for every <em>i</em> from 1 to <em>n</em>).</li>\n  </ul>\n</blockquote>\n\n<p>In other words, at the beginning of each <code>try</code> statement:</p>\n\n<ul>\n<li>all assignments made to visible objects prior to entering the <code>try</code> statement must be complete, which requires a thread lock for a start, making it useful for debugging race conditions!</li>\n<li>the compiler isn\'t allowed to:\n\n<ul>\n<li>eliminate unused variable assignments which have definitely been assigned to before the <code>try</code> statement</li>\n<li>reorganise or coalesce any of it\'s <em>inner-assignments</em> (i.e. see my first link, if you haven\'t already done so).</li>\n<li>hoist assignments over this barrier, to delay assignment to a variable which it knows won\'t be used until later (if at all) or to pre-emptively move later assignments forward to make other optimisations possible...</li>\n</ul></li>\n</ul>\n\n<p>A similar story holds for each <code>catch</code> statement; suppose within your <code>try</code> statement (or a constructor or function it invokes, etc) you assign to that otherwise pointless variable (let\'s say, <em><code>garbage=42;</code></em>), the compiler can\'t eliminate that statement, no matter how irrelevant it is to the observable behaviour of the program. The assignment needs to have <em>completed</em> before the <code>catch</code> block is entered.</p>\n\n<p>For what it\'s worth, <code>finally</code> tells a similarly <em>degrading</em> story:</p>\n\n<p>12.3.3.14 Try-finally statements </p>\n\n<blockquote>\n  <p>For a <em>try</em> statement <em>stmt</em> of the form:</p>\n\n<pre><code>try try-block\nfinally finally-block\n</code></pre>\n  \n  <p>• The definite assignment state of <em>v</em>  at the beginning of <em>try-block</em> is the same as the definite assignment state of <em>v</em> at the beginning of <em>stmt</em>.<br>\n  • The definite assignment state of <em>v</em> at the beginning of <em>finally-block</em> is the same as the definite assignment state of <em>v</em> at the beginning of <em>stmt</em>.<br>\n  • The definite assignment state of <em>v</em> at the end-point of <em>stmt</em> is definitely assigned if (and only if) either: \n    o <em>v</em> is definitely assigned at the end-point of <em>try-block</em>\n    o <em>v</em> is definitely assigned at the end-point of <em>finally-block</em>\n  If a control flow transfer (such as a <em>goto</em> statement) is made that begins within <em>try-block</em>, and ends outside of <em>try-block</em>, then <em>v</em> is also considered definitely assigned on that control flow transfer if <em>v</em> is definitely assigned at the end-point of <em>finally-block</em>. (This is not an only if—if <em>v</em> is definitely assigned for another reason on this control flow transfer, then it is still considered definitely assigned.)</p>\n</blockquote>\n\n<p>12.3.3.15 Try-catch-finally statements </p>\n\n<blockquote>\n  <p>Definite assignment analysis for a <em>try</em>-<em>catch</em>-<em>finally</em> statement of the form:</p>\n\n<pre><code>try try-block\ncatch ( ... ) catch-block-1\n... \ncatch ( ... ) catch-block-n\nfinally finally-block\n</code></pre>\n  \n  <p>is done as if the statement were a <em>try</em>-<em>finally</em> statement enclosing a <em>try</em>-<em>catch</em> statement: </p>\n\n<pre><code>try { \n    try   \n    try-block\n    catch ( ... ) catch-block-1\n    ...   \n    catch ( ... ) catch-block-n\n} \nfinally finally-block\n</code></pre>\n</blockquote>\n'}]
['https://Stackoverflow.com/questions/52312', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4541/']