Catching ADO.NET errors
Tags: VB.NET, VB 2008, VB 2010, VB 2012, VB 2013
This lesson describes how to handle errors in ADO.NET
When you write some program you have to care about fixing any errors or problems that are detected by the language compiler. But, there is a some type of errors that do not happen during compile time.
They occur at runtime because the application is trying to e.g. open a connection to a non-existent database, open a file that doesn’t exist, or write to a file that is open in read-only mode. These type of errors are known as exceptions.
Exception handling is a technique that programmers use to avoid any runtime errors and to handle them. Try, catch, and finally are keywords that exception handling is mainly based on. All programs can have one try, followed by one or many catch blocks, and then end with one finally block.
Dim ConnectionString As String = _ "Data Source=SqlServerNameOrIP;Initial Catalog=DBName;Integrated Security=True" Dim connection As New SqlConnection(ConnectionString) Try connection.Open() '... Catch ex As SqlException ' do something with this type of exception Catch ex As DataException ' do something with this type of exception Catch ex As Exception ' if above exceptions are not thrown then it checkes the, ' System.Exception class which is the base class for all exceptions ' do something with this exception Finally connection.Close() End Try
The try block holds code that throw an error, while the catch block serves as a defensive mechanism and handles the error.
The code inside the finally block is executed no matter whether an exception is thrown or not inside the try or catch block. The best code statements for finally block consist of closing streams and connections.
'... Finally ' this block executes always connection.Close() End Try