×

VB.Net Programs

VB.Net program to demonstrate the finally block in exception handling

By Nidhi Last Updated : November 11, 2024

Finally block in exception handling in VB.Net

Here, we demonstrate the finally block in exception handling. The finally is always executed in the program either an exception is generated or not.

Program/Source Code:

The source code to demonstrate the finally block in exception handling is given below. The given program is compiled and executed successfully.

VB.Net code to demonstrate the example of finally block in exception handling

'Vb.Net program to demonstrate the finally block.

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)
        Finally
            Console.WriteLine("Finally block gets executed")
        End Try
    End Sub
End Module

Output

Object reference not set to an instance of an object.
Finally block gets executed
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. After that finally block get executed.

VB.Net Exception Handling Programs »


Comments and Discussions!

Load comments ↻





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