×

VB.Net Programs

VB.Net program to demonstrate the NullReferenceException

By Nidhi Last Updated : November 13, 2024

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()
        Try
            Dim S As New Sample()

            S = Nothing
            S.SayHello()
        Catch e As NullReferenceException
            Console.WriteLine(e.Message)
        End Try
    End Sub
End Module

Output

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

Explanation

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.