Home

Exception Handling in File Processing

   

Finally

To handle exceptions, we can use the Try, Catch, and Throw keywords. These allowed us to perform normal assignments in a Try section and then handle an exception, if any, in a Catch block. We also mentioned that, when you create a stream, the operating system must allocate resources and dedicate them to the file processing operations. Additional resources may be provided for the object that is in charge of writing to, or reading from, the stream. We also saw that, when the streaming was over, we should free the resources and give them back to the operating system. To do this, we called the Close() method of the variable that was using resources.

More than any other assignment, file processing is in prime need of exception handling. During file processing, there are many things that can go wrong. For this reason, the creation and/or management of streams should be performed in a Try block to get ready to handle exceptions that would occur. Besides actually handling exceptions, you can use a special keyword used free resources. This keyword is Finally.

The Finally keyword is used to create a section of an exception. Like Catch, a Finally block cannot exist by itself. It can be created following a Try section. The formula used would be:

try

Finally

End Try

Based on this, the Finally section has a body of its own, delimited by its curly brackets. Like Catch, the Finally section is created after the Try section. Unlike Catch, Finally never has parentheses and never takes arguments. Unlike Catch, the Finally section is always executed. Because the Finally clause always gets executed, you can include any type of code in it but it is usually appropriate to free the resources that were allocated previously. In the same way, you can use a finally section to free resources used when reading from a stream. Here are examples:

Imports System.IO

Public Class Exercise

    Private Sub btnSave_Click(ByVal sender As System.Object, _
                              ByVal e As System.EventArgs) _
                              Handles btnSave.Click
        Dim Filename As String = "Persons.prs"

        Dim PersonsStream As FileStream
        Dim PersonsWriter As BinaryWriter

        PersonsStream = New FileStream(Filename, FileMode.Create)
        PersonsWriter = New BinaryWriter(PersonsStream)

        Try
            PersonsWriter.Write(txtPerson1.Text)
            PersonsWriter.Write(txtPerson2.Text)
            PersonsWriter.Write(txtPerson3.Text)
            PersonsWriter.Write(txtPerson4.Text)
        Finally
            PersonsWriter.Close()
            PersonsStream.Close()
        End Try

        txtPerson1.Text = ""
        txtPerson2.Text = ""
        txtPerson3.Text = ""
        txtPerson4.Text = ""
    End Sub

    Private Sub btnOpen_Click(ByVal sender As Object, _
                              ByVal e As System.EventArgs) _
                              Handles btnOpen.Click

        Dim Filename As String = "Persons.prs"
        Dim PersonsStreamer As FileStream
        Dim PersonsReader As BinaryReader

        PersonsStreamer = New FileStream(Filename, FileMode.Open)
        PersonsReader = New BinaryReader(PersonsStreamer)

        Try
            txtPerson1.Text = PersonsReader.ReadString()
            txtPerson2.Text = PersonsReader.ReadString()
            txtPerson3.Text = PersonsReader.ReadString()
            txtPerson4.Text = PersonsReader.ReadString()
        Finally
            PersonsReader.Close()
            PersonsStreamer.Close()
        End Try
    End Sub
End Class

Of course, since the whole block of code starts with a Try section, it is used for exception handling. This means that you can add the necessary and appropriate Catch section(s) (but you don't have to).

Practical LearningPractical Learning: Finally Releasing Resources

  1. Right-click the form and click View Code
  2. Change the following two events :
    Private Sub btnClose_Click(ByVal sender As Object, _
                                   ByVal e As System.EventArgs) _
                                   Handles btnClose.Click
            Dim Filename As String
            Dim Answer As MsgBoxResult
            Dim IceCreamWriter As StreamWriter
    
            Answer = MsgBox("Do you want to save this order to remember it " & _
                            "the next time you come to " & _
                            "get your ice cream?", _
                            MsgBoxStyle.YesNo Or MsgBoxStyle.Question, _
                            "Ice Cream Vending Machine")
        If Answer = MsgBoxResult.Yes Then
            Filename = InputBox( _
                    "Please type your initials and press Enter", _
                    "Ice Cream Vending Machine", "AA", 100, 100)
            If Filename <> "" Then
                Filename = Filename & ".icr"
    
                IceCreamWriter = _
    	 My.Computer.FileSystem.OpenTextFileWriter(Filename, False)
    
                Try
                  IceCreamWriter.WriteLine(dtpOrderDate.Value.ToShortDateString())
                  IceCreamWriter.WriteLine(dtpOrderTime.Value.ToShortTimeString())
                        IceCreamWriter.WriteLine(cboFlavors.Text)
                        IceCreamWriter.WriteLine(cboContainers.Text)
                        IceCreamWriter.WriteLine(cboIngredients.Text)
                        IceCreamWriter.WriteLine(txtScoops.Text)
                        IceCreamWriter.WriteLine(txtOrderTotal.Text)
                Finally
                        IceCreamWriter.Close()
                End Try
    
                    MsgBox("The order has been saved")
                Else
                    MsgBox("The ice cream order will not be saved")
                End If
            End If
    
            MsgBox("Good Bye: It was a delight serving you")
            Close()
    End Sub
    
    Private Sub Exercise_Load(ByVal sender As Object, _
                                  ByVal e As System.EventArgs) _
                                  Handles Me.Load
            Dim OrderDate As String, OrderTime As String
            Dim SelectedFlavor As String
            Dim SelectedContainer As String
            Dim SelectedIngredient As String
            Dim Scoops As String, OrderTotal As String
            Dim Filename As String
            Dim IceCreamReader As StreamReader
    
            Filename = InputBox( _
                   "If you had previously ordered an ice cream here " & _
                   "and you want to order the same, please type your " & _
                   "initials and press Enter (otherwise, press Esc)", _
                   "Ice Cream Vending Machine", "", 100, 100)
            If Filename <> "" Then
                Filename = Filename & ".icr"
    
                IceCreamReader = _
    		My.Computer.FileSystem.OpenTextFileReader(Filename)
    
                ' Find out if this order was previously saved in the machine
                If My.Computer.FileSystem.FileExists(Filename) Then
                    ' If so, open it
    
                    Try
                        OrderDate = IceCreamReader.ReadLine()
                        OrderTime = IceCreamReader.ReadLine()
                        SelectedFlavor = IceCreamReader.ReadLine()
                        SelectedContainer = IceCreamReader.ReadLine()
                        SelectedIngredient = IceCreamReader.ReadLine()
                        Scoops = IceCreamReader.ReadLine()
                        OrderTotal = IceCreamReader.ReadLine()
    
                        ' And display it to the user
                        dtpOrderDate.Value = DateTime.Parse(OrderDate)
                        dtpOrderTime.Value = DateTime.Parse(OrderTime)
                        cboFlavors.Text = SelectedFlavor
                        cboContainers.Text = SelectedContainer
                        cboIngredients.Text = SelectedIngredient
                        txtScoops.Text = Scoops.ToString()
                        txtOrderTotal.Text = OrderTotal
                    Finally
                        IceCreamReader.Close()
                    End Try
    
                Else
                    MsgBox("It looks like you have not previously " & _
                                 "ordered an ice cream here")
                End If
            End If
        End Sub
    End Class
  3. Save the file

The .NET Framework Exception Handling Classes

 

The File Not Found Exception

In the previous lesson as our introduction to file processing, we behaved as if everything was alright. Unfortunately, file processing can be very strict in its assignments. Based on this, the .NET Framework provides various Exception-oriented classes to deal with almost any type of exception you can think of.

One of the most important aspects of file processing is the name of the file that will be dealt with. In some cases you can provide this name to the application or document. In some other cases, you would let the user specify the name of the path. Regardless of how the name of the file would be provided to the operating system, when this name is acted upon, the compiler is asked to work on the file. If the file doesn't exist, the operation cannot be carried. Furthermore, the compiler would throw an error. Here is an example:

private void btnOpen_Click(object sender, EventArgs e)

    Dim Filename as string  = "contractors.spr"
    Dim fstPersons as FileStream  = null
    Dim rdrPersons As BinaryReader  = null

    fstPersons = new FileStream(Filename, FileMode.Open)
    rdrPersons = new BinaryReader(fstPersons)

    try
    
        txtPerson1.Text = rdrPersons.ReadString()
        txtPerson2.Text = rdrPersons.ReadString()
        txtPerson3.Text = rdrPersons.ReadString()
        txtPerson4.Text = rdrPersons.ReadString()
    End 
    finally
    
        rdrPersons.Close()
        fstPersons.Close()
    End 
End 

Here is an example of an error that this would produce:

The FileNotFoundException exception is thrown when a file has not been found. If you click the Details button of the above type of error, you would find out that this is the type of error you get when you provide a wrong path or wrong file name:

File Not Found Exception

To handle the FileNotFoundException exception, you can create its Catch clause. Here is an example:

Private Sub btnOpen_Click(ByVal sender As Object, _
                              ByVal e As System.EventArgs) _
                              Handles btnOpen.Click

        Dim Filename As String = "People.prs"
        Dim PersonsStreamer As FileStream
        Dim PersonsReader As BinaryReader

        Try
            PersonsStreamer = New FileStream(Filename, FileMode.Open)
            PersonsReader = New BinaryReader(PersonsStreamer)

            Try
                txtPerson1.Text = PersonsReader.ReadString()
                txtPerson2.Text = PersonsReader.ReadString()
                txtPerson3.Text = PersonsReader.ReadString()
                txtPerson4.Text = PersonsReader.ReadString()
            Finally
                PersonsReader.Close()
                PersonsStreamer.Close()
            End Try

        Catch fnfEx As FileNotFoundException
            MsgBox("Error: " & fnfEx.Message _
                   & vbCrLf & _
                   "May be the file doesn't exist or you typed it wrong!")
        End Try
End Sub

Here is an example of what this would produce:

File Not Found Exception Handling

The IO Exception

As mentioned already, during file processing, anything could go wrong. If you don't know what caused an error, you can throw the IOException exception.

Practical LearningPractical Learning: Handling File Processing Exceptions

  1. To handle a FileNotFoundException exception, change the event as follows:
     
    Private Sub Exercise_Load(ByVal sender As Object, _
                                  ByVal e As System.EventArgs) _
                                  Handles Me.Load
            Dim OrderDate As String, OrderTime As String
            Dim SelectedFlavor As String
            Dim SelectedContainer As String
            Dim SelectedIngredient As String
            Dim Scoops As String, OrderTotal As String
            Dim Filename As String
            Dim IceCreamReader As StreamReader
    
            Filename = InputBox( _
                   "If you had previously ordered an ice cream here " & _
                   "and you want to order the same, please type your " & _
                   "initials and press Enter (otherwise, press Esc)", _
                   "Ice Cream Vending Machine", "", 100, 100)
            If Filename <> "" Then
                Filename = Filename & ".icr"
    
                Try
                    IceCreamReader = _
    		    My.Computer.FileSystem.OpenTextFileReader(Filename)
    
                    ' Find out if this order was previously saved in the machine
                    If My.Computer.FileSystem.FileExists(Filename) Then
                        ' If so, open it
    
                        Try
                            OrderDate = IceCreamReader.ReadLine()
                            OrderTime = IceCreamReader.ReadLine()
                            SelectedFlavor = IceCreamReader.ReadLine()
                            SelectedContainer = IceCreamReader.ReadLine()
                            SelectedIngredient = IceCreamReader.ReadLine()
                            Scoops = IceCreamReader.ReadLine()
                            OrderTotal = IceCreamReader.ReadLine()
    
                            ' And display it to the user
                            dtpOrderDate.Value = DateTime.Parse(OrderDate)
                            dtpOrderTime.Value = DateTime.Parse(OrderTime)
                            cboFlavors.Text = SelectedFlavor
                            cboContainers.Text = SelectedContainer
                            cboIngredients.Text = SelectedIngredient
                            txtScoops.Text = Scoops.ToString()
                            txtOrderTotal.Text = OrderTotal
                        Finally
                            IceCreamReader.Close()
                        End Try
    
                    Else
                        MsgBox("It looks like you have not previously " & _
                                     "ordered an ice cream here")
                    End If
    
                Catch ex As FileNotFoundException
                    MsgBox("There is no previous order with those initials")
                End Try
            End If
    End Sub
  2. Exercise the application and test it
  3. Close the form
 

Home Copyright © 2008-2016, FunctionX, Inc.