Foundations of Programming - Karl Seguin
Foundations of Programming - Karl Seguin
Foundations of Programming - Karl Seguin
Create successful ePaper yourself
Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.
Chapter 8 - Back to Basics: Exceptions<br />
SqlConnection connection = new SqlConnection(FROM_CONFIGURATION)<br />
SqlCommand command = new SqlCommand("SomeSQL", connection);<br />
connection.Open();<br />
command.ExecuteNonQuery();<br />
command.Dispose();<br />
connection.Dispose();<br />
If ExecuteNonQuery throws an exception, neither our command nor our connection will get disposed<br />
<strong>of</strong>. The solution is to use Try/Finally:<br />
SqlConnection connection;<br />
SqlCommand command;<br />
try<br />
{<br />
connection = new SqlConnection(FROM_CONFIGURATION)<br />
command = new SqlCommand("SomeSQL", connection);<br />
connection.Open();<br />
command.ExecuteNonQuery();<br />
}<br />
finally<br />
{<br />
if (command != null) { command.Dispose(); }<br />
if (connection != null) { connection.Dispose(); }<br />
}<br />
or the syntactically nicer using statement (which gets compiled to the same try/finally above):<br />
using (SqlConnection connection = new SqlConnection(FROM_CONFIGURATION))<br />
using (SqlCommand command = new SqlCommand("SomeSQL", connection))<br />
{<br />
connection.Open();<br />
command.ExecuteNonQuery();<br />
}<br />
The point is that even if you can't handle an exception, and you should centralize all your logging, you do<br />
need to be mindful <strong>of</strong> where exceptions can crop up - especially when it comes to classes that<br />
implement IDiposable.<br />
<strong>Foundations</strong> <strong>of</strong> <strong>Programming</strong> Copyright © <strong>Karl</strong> <strong>Seguin</strong> www.codebetter.com<br />
66