×

VB.Net Programs

VB.Net program to demonstrate the FileNotFoundException Exception

By Nidhi Last Updated : November 11, 2024

FileNotFoundException in VB.Net

Here, we will read data from a text file if the specified file does not exist then a FileNotFoundException will be generated and print an appropriate message on the console screen.

Program/Source Code:

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

VB.Net code to demonstrate the example of FileNotFoundException

'Vb.Net program demonstrates the File Not Found exception.

Imports System.IO

Module Module1
    Class Sample
        Private fileName As String = "SampleFile.txt"

        Public Sub PrintData()
            Dim luckyNum As Integer = 0
            Dim msg As String = ""

            Try
                Dim f As FileStream = File.Open(fileName, FileMode.Open)
                Dim breader As New BinaryReader(f)

                luckyNum = breader.ReadInt32()
                msg = breader.ReadString()

                Console.WriteLine("Lucky Number : " & luckyNum)
                Console.WriteLine("String       : " & msg)

                f.Close()

            Catch e As FileNotFoundException
                Console.WriteLine("SampleFile.txt does not exist")
            End Try
        End Sub
    End Class

    Sub Main()
        Dim S As New Sample()
        S.PrintData()
    End Sub
End Module

Output

Specified string contains a number
Press any key to continue . . .

Explanation

In the above program, we created a module Module1 that contains a Sample class and a Main() function.

The Sample class contains a method PrintData(), In the PrintData() method, we read the data from the "SampleFile.txt" text file. If the "SampleFile.txt" text file does not exist, then the File Not Found exception will be generated, and print the appropriate message on the console screen.

The Main() function is the entry point for the program. Here, we created the object of Sample class and called PrintData().

VB.Net Exception Handling Programs »


Comments and Discussions!

Load comments ↻





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