Parag’s Den

Dedicated to my adored friends…..

Asp.Net (Always use Try..Catch..Finally)

Posted by paragdongre on November 6, 2007


Always use Try..Catch..Finally mechanism when you are dealing with scenarios which can raise an exception. When ever you bind, use a DataReader. You can also use a dataset which is disconnected in nature. The code written in Finallly block will always get executed. So we can have any cleanup routines inside the finally block. The following example, binds a DataReader to a DataGrid (DG_DblClick). In the finally block, we close both DataReader and Connection Object.

Note “Even though, .NET have inbuild Garbage Collector, it will be a good practice to close all open resources, once your task is over”

Try

     myConnection.Open()
     myDataReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection)
     DG.DataSource = myDataReader
     DG.DataBind()

Catch SQLexc As SqlException
     lblStatus.Text = “Error while Generating Data. Error is ” & SQLexc.ToString()

Finally
     if Not myDataReader Is Nothing Then
          myDataReader.Close()
     End If

     If Not myConnection Is Nothing AndAlso ((myConnection.State And ConnectionState.Open) = ConnectionState.Open) Then
          myConnection.Close()
     End If

End Try

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: