×

VB.Net Programs

VB.Net program to demonstrate the IndexOutOfRangeException

By Nidhi Last Updated : November 11, 2024

System.IndexOutOfRangeException in VB.net when using arrays

Here, we demonstrate the index out of bounds exception. Here, we will access the element of the array from the index which is out of bounds of the array then the program will generate an exception that will be caught in the "catch" block.

Program/Source Code:

The source code to demonstrate the IndexOutOfRangeException is given below. The given program is compiled and executed successfully.

VB.Net code to demonstrate the example of IndexOutOfRangeException

'Vb.Net program to demonstrate the IndexOutOfRangeException.

Module Module1
    Sub Main()
        Dim intArray() As Integer = {50, 40, 30, 20, 10}
        Dim sum As Integer = 0

        Try
            For iLoop = 0 To 5 Step 1
                sum += intArray(iLoop)
            Next
            Console.WriteLine("Sum of array elements: {0}", sum)
        Catch e As IndexOutOfRangeException
            Console.WriteLine(e.Message)
        End Try
    End Sub
End Module

Output

Index was outside the bounds of the array.
Press any key to continue . . .

Explanation

In the above program, here we created a module Module1. The Module1 contains Main() function.

The Main() is the entry point for the program, here we created an array of 5 integers. Here we want to calculate the sum of all elements.

Here, we defined the Try block to handle exceptions. The above will generate IndexOutOfRangeException because we are trying to access the element from index 5, which is not exist in the array. Then the generated exception will be caught by catch block and print the appropriate message on the console screen.

VB.Net Exception Handling Programs »


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.