Note that there are some explanatory texts on larger screens.

plurals
  1. POUse case for try-catch-finally with both catch and finally
    primarykey
    data
    text
    <p>I understand how <strong>try-catch</strong> works and how <strong>try-finally</strong> works, but I find myself using those (usually) in two completely different scenarios:</p> <ul> <li><strong>try-finally</strong> (or <code>using</code> in C# and VB) is mostly used around some medium-sized code block that uses some resource that needs to be disposed properly.</li> <li><strong>try-catch</strong> is mostly used either <ul> <li>around a single statement that can fail in a very specific way or </li> <li>(as a catch-all) at a very high level of the application, usually directly below some user interface action.</li> </ul></li> </ul> <p>In my experience, cases where a <strong>try-catch-finally</strong> would be appropriate, i.e., where the block in which I want to catch some particular exception is <em>exactly</em> the same block in which I use some disposable resource, are extremely rare. Yet, the language designers of <a href="http://msdn.microsoft.com/en-us/library/dszsf989.aspx" rel="noreferrer">C#</a>, <a href="http://msdn.microsoft.com/en-us/library/fk6t46tz.aspx" rel="noreferrer">VB</a> and <a href="http://java.sun.com/docs/books/tutorial/essential/exceptions/putItTogether.html" rel="noreferrer">Java</a> seem to consider this to be a highly common scenario; the VB designers <a href="http://blogs.msdn.com/lucian/archive/2010/02/15/req13-catches-in-using-blocks.aspx" rel="noreferrer">even think about adding <strong>catch</strong> to <code>using</code></a>.</p> <p>Am I missing something? Or am I just overly pedantic with my restrictive use of <strong>try-catch</strong>?</p> <hr> <p>EDIT: To clarify: My code usually looks like this (functions unrolled for clarity):</p> <pre><code>Try do something Aquire Resource (e.g. get DB connection) Try do something Try do something that can fail Catch SomeException handle expected error do something else... Finally Close Resource (e.g. close DB connection) do something Catch all handle unexpected errors </code></pre> <p>which just seems to make much more sense than putting any of the two catches on the same level as <em>finally</em> just to avoid indentation.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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