Home

Exception Handling in File Processing

  

Finally

So far, to handle exceptions, we were using 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.

In the previous lesson, we 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. As we will see in the next section, 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, SEH provides 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 earlier. Here is an example:

Imports System
Imports System.IO

Public Class Exercise
    Public Shared Sub main()
        Dim NameOfFile As String = "Members.clb"

        Dim fstPersons As FileStream = New FileStream(NameOfFile, FileMode.Create)
        Dim wrtPersons As BinaryWriter = New BinaryWriter(fstPersons)

        Try

            wrtPersons.Write("James Bloch")
            wrtPersons.Write("Catherina Wallace")
            wrtPersons.Write("Bruce Lamont")
            wrtPersons.Write("Douglas Truth")
        Finally
            wrtPersons.Close()
            fstPersons.Close()
        End Try
    End Sub
End Class

In the same way, you can use a Finally section to free resources used when reading from a stream:

Imports System
Imports System.IO

Public Class Exercise
    Public Shared Sub main()
        Dim NameOfFile As String = "Members.clb"
        Dim strLine As String

        Dim fstMembers As FileStream = New FileStream(NameOfFile, FileMode.Open)
        Dim rdrMembers As BinaryReader = New BinaryReader(fstMembers)

        Try
            strLine = rdrMembers.ReadString()
            Console.WriteLine(strLine)
            strLine = rdrMembers.ReadString()
            Console.WriteLine(strLine)
            strLine = rdrMembers.ReadString()
            Console.WriteLine(strLine)
            strLine = rdrMembers.ReadString()
            Console.WriteLine(strLine)
        Finally
            rdrMembers.Close()
            fstMembers.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.

 
 
 

 

.NET Framework Exception Handling for File Processing

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 be asked to work on the file. If the file doesn't exist, the operation cannot be carried. Furthermore, the compiler would throw an error. There are many other exceptions that can thrown as a result of something going bad during file processing:

FileNotFoundException: The exception thrown when a file has been found is of type FileNotFoundException. Here is an example of handling it:

Imports System
Imports System.IO

Public Class Exercise
    Public Shared Sub main()
        Dim NameOfFile As String = "Associates.clb"
        Dim strLine As String

        Try
            Dim fstMembers As FileStream = New FileStream(NameOfFile, FileMode.Open)
            Dim rdrMembers As BinaryReader = New BinaryReader(fstMembers)
            Try

                strLine = rdrMembers.ReadString()
                Console.WriteLine(strLine)
                strLine = rdrMembers.ReadString()
                Console.WriteLine(strLine)
                strLine = rdrMembers.ReadString()
                Console.WriteLine(strLine)
                strLine = rdrMembers.ReadString()
                Console.WriteLine(strLine)
            Finally
                rdrMembers.Close()
                fstMembers.Close()
            End Try
        Catch ex As FileNotFoundException

            Console.WriteLine("Error: " + ex.Message)
            Console.WriteLine("May be the file doesn't exist or you typed it wrong!")
        End Try
    End Sub
End Class

Here is an example of what this would produce:

Error: Could not find file "C:\Programs\MSVB .NET 2003\Project11\bin\Associates.
clb".
May be the file doesn't exist or you typed it wrong!

IOException: 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.

 

 
 
   
 

Previous Copyright © 2008-2016, FunctionX, Inc., Inc. Next