Visual Basic Try Catch Statement

In visual basic, Try Catch statement is useful to handle unexpected or runtime exceptions which will occur during execution of the program. The Try-Catch statement will contain a Try block followed by one or more Catch blocks to handle different exceptions.

 

In visual basic, whenever an exception occurred in the Try block, then the CLR (common language runtime) will look for the catch block that handles an exception. In case, if currently executing method does not contain such a Catch block, then the CLR will display an unhandled exception message to the user and stops the execution of the program.

Visual Basic Try Catch Syntax

Following is the syntax of handling errors in visual basic using Try, Catch blocks.

 

Try

' Code that may cause exception

Catch ex As Exception

' Exception handling

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.

 

In Try-Catch statement, the Catch block will execute only when an exception occurred in the code that is guarded by Try block.

Visual Basic Try Catch Example

Following is the example of using Try-Catch statement in visual basic to handle the exceptions.

 

Module Module1

    Sub Main(ByVal args As String())

        Dim name As String = Nothing

        Try

            If name.Length > 0 Then ' Exception will occur

                Console.WriteLine("Name: " & name)

            End If

        Catch ex As Exception

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

        End Try

        Console.ReadLine()

    End Sub

End Module

If you observe the above code, we used Try and Catch blocks to handle runtime or unexpected errors during the 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.

 

When we execute the above code, we will get the result as shown below.

 

Exception: Object reference not set to an instance of an object.

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

 

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

Visual Basic Try with Multiple Catch Blocks

In the above Try-Catch statement example, we used only a single Catch block with the Exception base class argument to handle all the exceptions.

 

In case, if we want to handle a different type of exceptions in different ways, then we can specify multiple Catch blocks with different exception types in the same Try-Catch statement and this process called an exception filtering.

 

If we define multiple Catch blocks with a Try statement, then the first Catch statement that can handle an exception will be executed, any following Catch statements that are even more compatible to handle an exception will be ignored so the order of Catch blocks must be always from most specific to least specific.

 

Following is the example of defining multiple catch blocks in a Try-Catch statement to handle different exceptions in different ways.

 

Module Module1

    Sub Main(ByVal args As String())

        Try

            Console.WriteLine("Enter x value:")

            Dim x As Integer = Integer.Parse(Console.ReadLine())

            Console.WriteLine("Enter y value:")

            Dim y As Integer = Integer.Parse(Console.ReadLine())

            Console.WriteLine(x / y)

        Catch ex As FormatException

            Console.WriteLine("Input string was not in a correct format.")

        Catch ex As InvalidOperationException

            Console.WriteLine("Not a valid numbers to perform operation")

        Catch ex As DivideByZeroException

            Console.WriteLine("Cannot Divide By Zero")

        End Try

        Console.ReadLine()

    End Sub

End Module

If you observe the above example, we defined multiple Catch blocks to handle different exception types so that we can easily get know what exact error it is and we can fix it easily.

 

When we execute the above example, we will get the result as shown below.

 

Enter x value:

10

Enter y value:

0

Cannot Divide By Zero

This is how we can use multiple Catch blocks with a single Try block to handle different types of exceptions based on our requirements.

Visual Basic Invalid Catch Blocks

In visual basic, defining a parameterless Catch block (Catch) and Catch block with an exception argument (Catch ex As Exception) are not allowed in the same Try-Catch statement because both will do the same thing.

 

Following is the example of defining an invalid Catch blocks in same Try-Catch statement.

 

Try

' Code that may cause an exception

Catch

' Exception Handling

Catch ex As Exception

' Exception Handling

End Try

In case, if we use a parameterless catch block (Catch) or Catch block with an exception argument (Catch ex As Exception) with other Catch blocks, then those parameters must be last otherwise we will get a compile-time error.

 

Following is the invalid way of defining a multiple catch blocks with a parameterless Catch block in same Try-Catch statement.

 

Try

' Code that may cause an exception

Catch

' Exception Handling

Catch ex As FormatException

' Exception Handling

Catch ex As InvalidOperationException

' Exception Handling

End Try

The following are the few points which we need to consider while defining a multiple Catch blocks.

 

  • Multiple Catch blocks with the same exception type are not allowed.
  • Defining a parameterless catch block (Catch) and catch block with an exception argument (Catch ex As Exception) are not allowed in the same try-catch statement because both will do the same thing.
  • While defining multiple catch blocks, the order of catch blocks must be always from most specific to least specific.
  • A parameterless catch block (Catch) or catch block with an exception argument (Catch ex As Exception) must be the last block if we use it with other catch blocks otherwise we will get a compile-time error.

Visual Basic Nested Try-Catch Statements

In visual basic, we can define a Try-Catch statement within another Try-Catch statement based on our requirements. In nested Try-Catch statements, if there isn’t any inner Catch block with an appropriate exception type, then the exception will flow to the outer Catch block.

 

Following is the example of defining nested Try-Catch statements in visual basic.

 

Module Module1

    Sub Main(ByVal args As String())

        Try

            Try

                Console.WriteLine("Enter x value:")

                Dim x As Integer = Integer.Parse(Console.ReadLine())

                Console.WriteLine("Enter y value:")

                Dim y As Integer = Integer.Parse(Console.ReadLine())

                Console.WriteLine(x / y)

            Catch ex As FormatException

                Console.WriteLine("Input string was not in a correct format.")

            End Try

        Catch ex As Exception

            Console.WriteLine("Exception: " & ex.Message)

        End Try

        Console.ReadLine()

    End Sub

End Module

If you observe the above example, we defined a Try-Catch statement within another Try-Catch statement. Here, if we get any exception other than FormatException in an inner Try-Catch statement, the exception will flow to outer Catch block until it finds an appropriate exception filter.

 

When we execute the above program, we will get the result like as shown below.

 

Enter x value:

10

Enter y value:

0

Exception: Attempted to divide by zero.

If you observe the above result, the inner Try-Catch statement has failed to handle the exception so the catch block in the outer Try-Catch statement has been handled the exception.

Visual Basic Try-Catch Overview

The following are the important points which we need to remember about the Try-Catch statement.

 

  • In Try-Catch statement, the Try block will hold the code that may raise an exception and in the Catch block, exception handling can be done.
  • The Try-Catch statement will contain a Try block followed by one or more Catch blocks to handle different exceptions.
  • In visual basic, whenever an exception occurred in the Try block, then the CLR (common language runtime) will look for the appropriate Catch block that handles an exception.
  • In visual basic, we can use nested Try-Catch statements.
  • In nested Try-Catch statements, if there isn’t any inner Catch block with an appropriate exception type, then the exception will be caught by an outer Catch block.