Exception classes for file I/O in VB.NET

In this article we will handle the exceptions that occur during the I/O operations.
  • 2567

Most of the time, you can write code to avoid the Exceptions that can occur when you perform I/O operations. For example, you can avoid a DirectoryNotFoundException by using the Exists method of the Directory class to be sure that the directory exists before you try to use it in the file path for a new file stream.

When handling I/O exceptions, it's common to use a Finally block. In this block, it's common to use the stream's Close method to close all the  streams that are open. This frees the resources that are used to access the stream. To start, the statement just before the Try block declare a variable for the stream. That way, this variable is available to the Catch blocks and the Finally block.

Code that uses exception classes

Imports System.IO
Imports System.Windows.Forms 
Module Module1 
    Sub Main()
        Dim dirpath As String = "c:\VB 2008\Files\"
        Dim filepath As String = dirpath & "products.txt"
        Dim fs As FileStream
            fs = New FileStream(filepath, FileMode.Open) 
        Catch ex As FileNotFoundException
            MessageBox.Show(filepath & "not found.", "file not found")
        Catch ex As DirectoryNotFoundException
            MessageBox.Show(dirpath & "not found.", "directory not found")
        Catch ex As IOException
            MessageBox.Show(ex.Message, "IO Exception")
            If fs IsNot Nothing Then
            End If
        End Try
    End Sub
End Module

A dialog box appears as output and displays the error message:




More Articles

© 2020 DotNetHeaven. All rights reserved.