VB.Net program to demonstrate the FileNotFoundException Exception

Here, we are going to demonstrate the FileNotFoundException Exception in VB.Net?
Submitted by Nidhi, on January 06, 2021

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 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 = ""

                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)


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

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


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


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().

Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.