Home


.Net, SQL and softball. Musings of a software developer with a softball problem

Wednesday, July 9, 2008

Using statement versus Try/Catch

So I had a code review this morning and learned of a better way to handle some of my error handling and garbage collecting.

I was using a try/catch/finally block to handle catching errors when calling a database function and then doing all my disposes and clean up in the finally. Now if I was doing something with the error rather than just re-throwing it up to the next layer that would have been fine. But since I wasn't really handling the error at this point there was no reason for me to have all the over head of a try catch block. And as for my disposes there were more elegant solutions to make sure I dispose of all my objects. Enter the Using statement.

This was the first I heard of it. I have spent the afternoon changing most of my data layer code over to it. It allows you to explicitly define a variable that will automatically dispose of itself once it gets to the end of the using block. So it has a very narrow scope. And as for the errors, since those were bubbling up and being caught at the next level there was no need for me to catch them here.

So my code went from this using try/catch/finally:
Dim oConn As New OracleConnection
Dim oComm As OracleCommand

oConn.ConnectionString = "connString"

Try
oConn.Open()

oComm = New OracleCommand("procedurename", oConn)
oComm.CommandType = CommandType.StoredProcedure

oComm.Parameters.AddWithValue("PARAM", param)

oComm.ExecuteNonQuery()

Catch ex As Exception
Throw ex
Finally
oConn.Close()
oConn = Nothing
oComm = Nothing
End Try

To this using the 'Using statement':
using oConn as new OracleConnection("connString")
using oComm as New OracleCommand("procedurename", oConn)
oConn.Open()

oComm.CommandType = CommandType.StoredProcedure
oComm.Parameters.AddWithValue("PARAM", param)

oComm.ExecuteNonQuery()

end using
end using

I think it makes it look a lot cleaner and it removed about 10-15 lines of code per function.

Labels:

posted by Tom Becker at

0 Comments:

Post a Comment

<< Home

Powered by Blogger

Subscribe to
Posts [Atom]

Name: Tom Becker
Location: Richmond, VA, United States