Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You would use it to ensure some actions occur after the <code>try</code> content or on an exception, but when you don't wish to consume that exception.</p> <p>Just to be clear, this doesn't hide exceptions. The <code>finally</code> block is run before the exception is propagated up the call stack.</p> <p>You would also inadvertently use it when you use the <code>using</code> keyword, because this compiles into a <code>try-finally</code> (not an exact conversion, but for argument's sake it is close enough).</p> <pre><code>try { TrySomeCodeThatMightException(); } finally { CleanupEvenOnFailure(); } </code></pre> <p>Code running in <code>finally</code> is not guaranteed to run, however the case where it isn't guaranteed is fairly edge - I can't even remember it. All I remember is, if you are in that case, chances are very good that not running the <code>finally</code> isn't your biggest problem :-) so basically don't sweat it.</p> <p><strong>Update from Tobias:</strong> <code>finally</code> will not run if the process is killed.</p> <p><strong>Update from Paddy:</strong> <a href="https://stackoverflow.com/questions/111597/conditions-when-finally-does-not-execute-in-a-net-try-finally-block">Conditions when finally does not execute in a .net try..finally block</a></p> <p>The most prevalent example you may see is disposing of a database connection or external resource even if the code fails:</p> <pre><code>using (var conn = new SqlConnection("")) // Ignore the fact we likely use ORM ;-) { // Do stuff. } </code></pre> <p>Compiles into <em>something</em> like:</p> <pre><code>SqlConnection conn; try { conn = new SqlConnection(""); // Do stuff. } finally { if (conn != null) conn.Dispose(); } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload