Home »
VB.Net »
VB.Net Programs
VB.Net program to demonstrate the InvalidOperationException
Here, we are going to demonstrate the InvalidOperationException in VB.Net.
Submitted by Nidhi, on January 07, 2021
Here, we will demonstrate the InvalidOperationException and print an appropriate message on the console screen.
Program/Source Code:
The source code to demonstrate the InvalidOperationException is given below. The given program is compiled and executed successfully.
'Vb.Net program demonstrate the InvalidOperationException.
Imports System.IO
Module Module1
Sub Main()
Try
Dim nums As New List(Of Integer)()
nums.Add(1)
nums.Add(2)
nums.Add(3)
nums.Add(4)
nums.Add(5)
For Each num In nums
Dim square As Integer
square = Math.Pow(num, 2)
Console.WriteLine("Adding {0} to the List", square)
nums.Add(square)
Next
Catch ex As InvalidOperationException
Console.WriteLine("Exception: " & ex.Message)
End Try
End Sub
End Module
Output:
Adding 1 to the List
Exception: Collection was modified; enumeration operation may not execute.
Press any key to continue . . .
Explanation:
In the above program, we created a module Module1 that contains a Main() function.
The Main() function is the entry point for the program. Here, we created a list collection of integer numbers and then calculated the square of a number and add the square of the number into the list then Invalid operation exception gets generated and caught in the catch block and print the appropriate message on the console screen.
TOP Interview Coding Problems/Challenges