Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy doesn't 'using' have a catch block?
    text
    copied!<p>I understand the point of "using" is to guarantee that the Dispose method of the object will be called. But how should an exception within a "using" statement be handled? If there is an exception, I need to wrap my "using" statement in a try catch. For example:</p> <p><br>Lets say there is an exception created in the creation of the object inside the using parameter</p> <pre><code> try { // Exception in using parameter using (SqlConnection connection = new SqlConnection("LippertTheLeopard")) { connection.Open(); } } catch (Exception ex) { } </code></pre> <p>Or an Exception within the using scope</p> <pre><code> using (SqlConnection connection = new SqlConnection()) { try { connection.Open(); } catch (Exception ex) { } } </code></pre> <p>It seems like if I already need to handle an exception with a try catch, that maybe I should just handle the disposing of the object as well. In this case the "using" statement doesn't seem to help me out at all. How do I properly handle an exception with "using" statement? Is there a better approach to this that I'm missing?</p> <pre><code> SqlConnection connection2 = null; try { connection2 = new SqlConnection("z"); connection2.Open(); } catch (Exception ex) { } finally { IDisposable disp = connection2 as IDisposable; if (disp != null) { disp.Dispose(); } } </code></pre> <p>Could the "using" keyword syntax be a little more sugary... <br>It sure would be nice to have this:</p> <pre><code> using (SqlConnection connection = new SqlConnection()) { connection.Open(); } catch(Exception ex) { // What went wrong? Well at least connection is Disposed } </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