Subscribe

RSS Feed (xml)

Catching Exceptions

In <script runat="server" /> block or codebehind:


Private Sub Page_Load(Source As Object, E As EventArgs)


Dim _Connection As New


SqlConnection("Server=localhost;Database=pubs;uid=sa;pwd=;")


Dim _Command As New SqlCommand("Select * From Authors", _Connection)


Try


'_Connection.Open commented to cause an exception


'_Connection.Open()


DG1.DataSource = _Command.ExecuteReader(CommandBehavior.CloseConnection)


DG1.DataBind()


Catch _Error As Exception


MessageLabel.Text = _Error.Message


Finally


_Connection.Close()


End Try


End Sub


You can also provide multiple Catch statements, as shown here:


Private Sub Page_Load(Source As Object, E As EventArgs)


'Error has been produced in the connection


'string by writing "Server=localhos" (no 't')



Dim _Connection As New




SqlConnection("Server=localhos;Database=pubs;uid=sa;pwd=;")


Dim _Command As New SqlCommand("Select * From Authors", _Connection)


Try


_Connection.Open()


DG1.DataSource = _Command.ExecuteReader(CommandBehavior.CloseConnection)


DG1.DataBind()


Catch _SqlError As SqlException


MessageLabel.Text = _SqlError.Message


Catch _Error As Exception


MessageLabel.Text= _Error.Message


Finally


_Connection.Close()


End Try


End Sub


Comments


The Try/Catch/Finally block is the best approach towards error handling. It provides a


structured error-handling technique that was not available in previous versions of Visual


Basic.The Try block is provided with the code that is to be run.The Catch block is for


catching the exceptions raised by any line of code in the Try block.The Finally block


is executed under both conditions-either when the Try section successfully executes or


when an error occurs and is passed to the Catch block. It is for this reason that the


Close() method of the connection object has been coded in the Finally block, so as to


ensure that under both cases (whether successful or unsuccessful), the connection to the


data store is closed.


Multiple Catch statements can also be provided to capture different types of errors


raised by objects. In the second code listing, the exceptions that would be related to


SqlClient objects are going to be captured by the Catch statement having an object of


the SqlException class. All other exceptions are caught by the second catch statement


provided in the Try block.


The order of the Catch statements is very important. Make sure you put the more


generalized Catch exceptions after the more specific exceptions. For example, in the second


code listing, SqlException is a subclass of Exception, and so is more specific.Thus,


its Catch block occurs above the more generic exception's Catch block. If the order


were reversed, the SqlException Catch block would never be reached, because the


exception block would always catch a SqlException that was thrown.




Technorati :

No comments:

Archives

Variety in the Web World