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