Visual Basic Try Catch Finally Statements

In visual basic, the try-catch-finally statement is useful to handle unexpected or runtime exceptions which will occur during execution of the program.

 

In try-catch-finally statement, the Try block is used to hold the code that may cause an exception, Catch block to handle exceptions and the Finally block is used to clean up or release any resources that are allocated in a Try block. For example, close database connections or any streams or files that are opened in Try block.

 

In visual basic, the finally block will always come after Try or Catch blocks and the Finally block will always execute even if an exception occurred or not and it is useful to clean up or dispose of unmanaged objects based on the requirements.

Visual Basic Try Catch Finally Syntax

Following is the syntax of handling errors in visual basic using Try-Catch-Finally statement.

 

Try

' Code that may cause exception

Catch ex As Exception

' Exception handling

Finally

' Cleanup resources

End Try

As per the above syntax, the Try block will contain the guarded code that may cause an exception so that if any errors occurred in our code, then immediately the code execution will be moved to Catch block to handle those exceptions.

 

After completion of Try or Try & Catch blocks, the Finally block will always be executed even if an exception occurred or not and it is useful to clean up or release unmanaged resources.

 

In Try-Catch-Finally statement, only one Try & Finally blocks are allowed but, we can use multiple catch blocks to handle different exception types.

 

In visual basic, the Try block must always be followed by Catch or Finally or both blocks otherwise we will get a compile-time error.

Visual Basic Try-Catch-Finally Example

Following is the example of handling exceptions in visual basic using Try-Catch-Finally statement.

 

Imports System.IO

 

Module Module1

    Sub Main(ByVal args As String())

        Dim fpath As String = "D:\Test.txt"

        Dim sr As StreamReader = New StreamReader(fpath)

        Try

            Dim txt As String

            While txt IsNot Nothing

                Console.WriteLine(txt)

            End While

        Catch ex As Exception

            Console.WriteLine("Exception: {0}", ex.Message)

        Finally

            If sr IsNot Nothing Then

                sr.Close()

            End If

        End Try

        Console.ReadLine()

    End Sub

End Module

If you observe the above code, we used Try, Catch and Finally blocks to handle runtime or unexpected errors during execution of the program. Here, we wrote a code that may throw an exception inside of Try block and in Catch block we are handling the exception. As discussed, the Finally block will execute after completion of Try or Catch block execution and release the required resources.

 

This is how we can use Try-Catch-Finally blocks to handle unexpected or runtime exceptions based on our requirements.