VB.Net program to demonstrate the NullReferenceException

Here, we are going to demonstrate the NullReferenceException in VB.Net.
Submitted by Nidhi, on January 05, 2021 [Last updated : March 08, 2023]

VB.Net - NullReferenceException

Here, we demonstrate the NullReferenceException. Here, we will call a method by a reference that contains a null value. Then exceptions will be generated by the program.

Program/Source Code:

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

VB.Net code to demonstrate the example of NullReferenceException

'Vb.Net program to demonstrate the NullReferenceException.

Module Module1
    Class Sample
        Public Sub SayHello()
            Console.WriteLine("Hello World")
        End Sub
    End Class

    Sub Main()
            Dim S As New Sample()

            S = Nothing
        Catch e As NullReferenceException
        End Try
    End Sub
End Module


Object reference not set to an instance of an object.
Press any key to continue . . .


In the above program, here we created a module Module1. In Module1 we created a class Sample that contains SayHello() method.

The Main() is the entry point for the program, here we created the object of Sample class and then assigned the Nothing in the object and then called the SayHello() method then it will generate null reference exception that will be caught by catch block and print an appropriate message on the console screen.

VB.Net Exception Handling Programs »

Comments and Discussions!

Load comments ↻

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