Erros and Catching Them in Visual Basic .NET
Tags: VB.NET, VB 2008, VB 2010, VB 2012, VB 2013
This lesson describes how to handle errors in Visual Basic .NET
Error handling is a very important part of any application.
In Visual Basic, the error mechanism is based on the concept of exceptions that can be thrown to raise an error and caught when the error is handled.
If you don't have an error handling in your code and an error occurs, your users receive a message about an unhandled exception, and then the program may terminate.
This message is not a user-friendly and does not inform the users about the true nature of the error or how to resolve it.
The unhandled exception could also cause users to lose the data that they were working with which can be very frustrating.
The structured error handling statements that Visual Basic offers is a great way to organize blocks of code in a structure that handles errors.
This mechanism is incorporated with the Try... Catch... Finally block and helps you to incorporate error handling into your programs with very little effort.
Esentially you execute the code that might throw an exception in the Try block, and you handle the errors in the Catch block.
The Finally block, which is optional, is always executed if present and helps you cleanup your code regardless of whether an error has occurred.
Usually in the Finally block you keep your dispose and close methods like connection.Close() that unsures that your connection is closed no matter what error you get in the Try block.
Dim connection As New SqlConnection("connection_string") Try connection.Open() Dim command As SqlCommand = connection.CreateCommand command.CommandText = "SELECT FieldName FROM Table1" Dim reader As SqlDataReader = command.ExecuteReader While reader.Read ' Do something with the reader(0).ToString End While reader.Close() command.Dispose() Catch ex As Exception ' display the error Console.Write(ex.Message) Finally connection.Close() ' this code will be always executed End Try