<p>Syntax aside, what is the difference between</p>

<pre><code>try {
}
catch() {
}
finally {
    x = 3;
}
</code></pre>

<p>and </p>

<pre><code>try {
}
catch() {
}

x = 3;
</code></pre>

<p>edit: in .NET 2.0?</p>

<hr>

<p>so</p>

<pre><code>try {
    throw something maybe
    x = 3
}
catch (...) {
    x = 3
}
</code></pre>

<p>is behaviourally equivalent?</p>

[{'answer_id': 50621, 'author': 'Ryan Lanciaux', 'author_id': 1385358, 'author_profile': 'https://Stackoverflow.com/users/1385358', 'pm_score': 0, 'selected': False, 'text': '<p>So you can clean up any open connections, etc. initialized in the try block. If you opened a connection and then an exception occurred, that exception would not be properly closed. This type of scenario is what the finally block is for.</p>\n'}, {'answer_id': 50623, 'author': 'SCdF', 'author_id': 1666, 'author_profile': 'https://Stackoverflow.com/users/1666', 'pm_score': 3, 'selected': False, 'text': '<p>In Java:</p>\n\n<p>Finally always gets called, regardless of if the exception was correctly caught in catch(), or in fact if you have a catch at all.</p>\n'}, {'answer_id': 50627, 'author': 'Vinko Vrsalovic', 'author_id': 5190, 'author_profile': 'https://Stackoverflow.com/users/5190', 'pm_score': 6, 'selected': True, 'text': "<p>Depends on the language as there might be some slight semantic differences, but the idea is that it will execute (almost) always, even if the code in the try block threw an exception.</p>\n\n<p>In the second example, if the code in the catch block returns or quits, the x = 3 will not be executed. In the first it will.</p>\n\n<p>In the .NET platform, in some cases the execution of the finally block won't occur:\nSecurity Exceptions, Thread suspensions, Computer shut down :), etc.</p>\n"}, {'answer_id': 50628, 'author': 'Josh Hinman', 'author_id': 2527, 'author_profile': 'https://Stackoverflow.com/users/2527', 'pm_score': 5, 'selected': False, 'text': '<p>Well, for one thing, if you RETURN inside your try block, the finally will still run, but code listed below the try-catch-finally block will not.</p>\n'}, {'answer_id': 50629, 'author': 'NotMe', 'author_id': 2424, 'author_profile': 'https://Stackoverflow.com/users/2424', 'pm_score': 0, 'selected': False, 'text': '<p>The finally block is supposed to execute whether you caught the exception or not.\nSee <a href="http://neptune.netcomp.monash.edu.au/JavaHelp/howto/try_catch_finally.htm#whyFinally" rel="nofollow noreferrer">Try / Catch / Finally example</a></p>\n'}, {'answer_id': 50631, 'author': 'Mo.', 'author_id': 1870, 'author_profile': 'https://Stackoverflow.com/users/1870', 'pm_score': 2, 'selected': False, 'text': '<p>In the case, that the try and the catch are empty, there is no difference. Otherwise you can be sure, that the finally will be executed.</p>\n\n<p>If you, for example throw a new Exception in your catchblock (rethrow), than the assignment will only be executed, if it is in the finally-block.</p>\n\n<p>Normally a finally is used to clean up after yourself (close DB-connections, File-Handles and the likes).</p>\n\n<p>You should never use control-statements (return, break, continue) in a finally, as this can be a maintenance nightmare and is therefore considered bad practice</p>\n'}, {'answer_id': 50638, 'author': 'Moe', 'author_id': 3051, 'author_profile': 'https://Stackoverflow.com/users/3051', 'pm_score': 1, 'selected': False, 'text': '<p>The finally block will always be called (well not really <a href="http://thedailywtf.com/Articles/My-Tales.aspx" rel="nofollow noreferrer">always</a> ... ) even if an exception is thrown or a return statement is reached (although that may be language dependent). It\'s a way to clean up that you know will always be called.</p>\n'}, {'answer_id': 50649, 'author': 'crashmstr', 'author_id': 1441, 'author_profile': 'https://Stackoverflow.com/users/1441', 'pm_score': 0, 'selected': False, 'text': '<p><a href="https://stackoverflow.com/questions/50618/what-is-the-point-of-the-finally-block#50624">@Ed</a>, you might be thinking of something like a <code>catch(...)</code> that catches a non-specified exception in C++.</p>\n\n<p>But <code>finally</code> is code that will get executed no matter what happens in the <code>catch</code> blocks.</p>\n\n<p>Microsoft has a help page on <a href="http://msdn.microsoft.com/en-us/library/zwc8s4fz.aspx" rel="nofollow noreferrer">try-finally for C#</a></p>\n'}, {'answer_id': 50665, 'author': 'Mats Fredriksson', 'author_id': 2973, 'author_profile': 'https://Stackoverflow.com/users/2973', 'pm_score': 2, 'selected': False, 'text': '<p>The finally block is in the same scope as the try/catch, so you will have access to all the variables defined inside.</p>\n\n<p>Imagine you have a file handler, this is the difference in how it would be written.</p>\n\n<pre><code>try\n{\n   StreamReader stream = new StreamReader("foo.bar");\n   stream.write("foo");\n}\ncatch(Exception e) { } // ignore for now\nfinally\n{\n   stream.close();\n}\n</code></pre>\n\n<p>compared to</p>\n\n<pre><code>StreamReader stream = null;\ntry\n{\n    stream = new StreamReader("foo.bar");\n    stream.write("foo");\n} catch(Exception e) {} // ignore\n\nif (stream != null)\n    stream.close();\n</code></pre>\n\n<p>Remember though that anything inside finally isn\'t guaranteed to run. Imagine that you get an abort signal, windows crashes or the power is gone. Relying on finally for business critical code is bad.</p>\n'}, {'answer_id': 50672, 'author': 'osp70', 'author_id': 2357, 'author_profile': 'https://Stackoverflow.com/users/2357', 'pm_score': 0, 'selected': False, 'text': '<p>Any code in the finally is ran in the even in the event of an unhandled exception.  Typically the finally code is used to clean up local declarations of unmanaged code using .dispose().</p>\n'}, {'answer_id': 50685, 'author': 'Bartosz Bierkowski', 'author_id': 3666, 'author_profile': 'https://Stackoverflow.com/users/3666', 'pm_score': 3, 'selected': False, 'text': '<p>try catch <strong>finally</strong> is pretty important construct. You can be sure that even if an exception is thrown, the code in finally block will be executed. It\'s very important in handling external resources to release them. Garbage collection won\'t do that for you. In finally part you shouldn\'t have <em>return</em> statements or throw exceptions. It\'s possible to do that, but it\'s a bad practice and can lead to unpredictable results. </p>\n\n<p>If you try this example:</p>\n\n<pre><code>try {\n  return 0;\n} finally {\n  return 2;\n}\n</code></pre>\n\n<p>The result will be 2:)</p>\n\n<p>Comparison to other languages: <a href="http://www.gettingclever.com/2008/07/return-from-finally.html" rel="nofollow noreferrer">Return From Finally</a></p>\n'}, {'answer_id': 50701, 'author': 'Ian', 'author_id': 4396, 'author_profile': 'https://Stackoverflow.com/users/4396', 'pm_score': 1, 'selected': False, 'text': '<p>Finally blocks permit you, as a developer, to tidy up after yourself, regardless of the actions of preceeding code in the try{} block encountered errors, and have others have pointed out this, is falls mainly under the umbrella of freeing resources - closing pointers / sockets / result sets, returning connections to a pool etc.</p>\n\n<p>@mats is very correct that there is always the potential for "hard" failures - finally blocks shouldn\'t include mission critical code, which should always be done transactionally inside the try{}</p>\n\n<p>@mats again - The real beauty is that it allows you throw exceptions back out of your own methods, and still guarantee that you tidy up:</p>\n\n<pre><code>try\n{\nStreamReader stream = new StreamReader("foo.bar");\nmySendSomethingToStream(stream);\n}\ncatch(noSomethingToSendException e) {\n    //Swallow this    \n    logger.error(e.getMessage());\n}\ncatch(anotherTypeOfException e) {\n    //More serious, throw this one back\n    throw(e);\n}\nfinally\n{\nstream.close();\n}\n</code></pre>\n\n<p>So, we can catch many types of exception, process them differently (the first allows execution for anything beyond the try{}, the second effectively returns), but always neatly and tidily clear up.</p>\n'}, {'answer_id': 50705, 'author': 'wvdschel', 'author_id': 2018, 'author_profile': 'https://Stackoverflow.com/users/2018', 'pm_score': 3, 'selected': False, 'text': '<p>There are several things that make a finally block useful:</p>\n\n<ol>\n<li>If you return from the try or catch blocks, the finally block is still executed, right before control is given back to the calling function</li>\n<li>If an exception occurs within the catch block, or an uncaught type of exception occurs in the try block, the code in the finally block is still executed.</li>\n</ol>\n\n<p>These make finally blocks excellent for closing file handles or sockets.</p>\n'}, {'answer_id': 52247, 'author': 'Sean', 'author_id': 5446, 'author_profile': 'https://Stackoverflow.com/users/5446', 'pm_score': 1, 'selected': False, 'text': '<p>@iAn and @mats:</p>\n\n<p>I would not "tear down" anything in finally {} that was "set up" within the try {} as a rule.  Would be better to pull the stream creation outside of the try {}.  If you need to handle an exception on stream create this could be done in a greater scope.   </p>\n\n<pre><code>StreamReader stream = new StreamReader("foo.bar");  \ntry {\n    mySendSomethingToStream(stream);\n}\ncatch(noSomethingToSendException e) {\n    //Swallow this    \n    logger.error(e.getMessage());\n}\ncatch(anotherTypeOfException e) {\n    //More serious, throw this one back\n    throw(e);\n}\nfinally {\n    stream.close();  \n}\n</code></pre>\n'}, {'answer_id': 144780, 'author': 'Uri', 'author_id': 23072, 'author_profile': 'https://Stackoverflow.com/users/23072', 'pm_score': 0, 'selected': False, 'text': '<p>In Java, you use it for anything that you want to execute regardless of whether you used a "return", just ran through the try block, or had an exception caught.</p>\n\n<p>For example, closing a database session or a JMS connection, or deallocating some OS resource. </p>\n\n<p>I am guessing it is similar in .NET?</p>\n'}, {'answer_id': 58169320, 'author': 'Jacob Bruinsma', 'author_id': 930879, 'author_profile': 'https://Stackoverflow.com/users/930879', 'pm_score': 1, 'selected': False, 'text': "<p>This is not an answer, but a critique. This question is <em>old</em>, but this has always bothered me. I found it here for a reason. I've read every answer and it looks to me that nobody really thought it through.</p>\n<p>I really think there is no good point to <code>finally</code>, which may be why it didn't exist in programming languages until &quot;recently&quot;. Most of the examples stating <code>stream.close()</code> can cause null reference exceptions, so you still have to test if it's null.</p>\n<p>Yes, if you return from within <code>try{}</code>, <code>finally</code> still runs. But is that good practice? It seems like mental gymnastics, might as well bring <code>goto</code> back. Why not wait, and return after the block? All that <code>finally {}</code> does, is add two or three lines to your code.</p>\n"}]
['https://Stackoverflow.com/questions/50618', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5278/']