VB.Net program to demonstrate the IndexOutOfRangeException

Here, we are going to demonstrate the IndexOutOfRangeException in VB.Net.
Submitted by Nidhi, on January 05, 2021

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 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




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.