Transcript Slide 1

CO331 Visual Programming
Lecture 19: Simple file i/o
Exceptions – Error handling
Roger Sutton
[email protected]
1
Sequential files
These are the most basic type of file that generally holds human
readable text. Accordingly the contents of such files may be read
using, for example, Notepad.
A sequential file stores items of data one after another; each new
item of data being added to the end of the data already stored.
A sequential file is used, usually, when
• Its not expected to make changes to the data within the file
too often
• The file information is likely to be processed from start to
finish without the need to jump about within the file to
acquired particular items of data.
• It is acceptable to add new data to the end of the file.
CO331 Visual Programming
2
File class
Programs that involve file processing must include
Imports System.IO
at the beginning.
The methods of File class:
• OpenText
is used to open an existing file
E.g.
File.OpenText(“U:\home\units\co331\aOldFile.txt”)
If the file does not exist then a runtime error will occur.
• CreateText
is used to create a new text file or overwrite an existing file.
E.g.
File.CreateText (“U:\home\units\co331\aNewFile.txt”)
CO331 Visual Programming
3
Streams
The term ‘stream’ is used in the sense of a stream of data flowing in
or out of a program.
• To process data in an existing file it is necessary to:
 Open the file
 Read (input) the data item-by-item from the file into variables
 Close the file on completion
• To transfer data from variables into a file, it is necessary to:
 Open the file
 Output (write) individual items in the required sequence to
the file
 Close the file on completion
CO331 Visual Programming
4
StreamReader Class
- will be used to read lines of text from a file.
The ReadLine method of StreamReader reads a whole line of text
into a string, excluding the end-of-line marker.
E.g.
CO331 Visual Programming
5
StreamWriter Class
The StreamWriter class has two main methods:
Write, and WriteLine
Both write a string to file, but WriteLine adds an end-of-line
marker after the string. WriteLine can also be used with no
argument to terminate a line with an end-of-line marker.
E.g.
CO331 Visual Programming
6
File searching
Searching a file for an item that satisfies some condition is
quite common.
E.g. Suppose we have a file of examination marks obtained
by named students:
Smith, 43, 67
Jones, 87, 99
Patel, 54, 32
Sutton, 65, 74
etc…
and we wish to obtain the marks of a particular student
from the file and display them.
CO331 Visual Programming
7
File searching - example
The process may be expressed in structured English as:
found = False
While (more lines to read) And found = False
read line
split line into three fields
If first field matches name Then
found = True
display other fields in labels
End If
End While
If Not found Then
display a warning
End If
CO331 Visual Programming
8
E.g. File searching - Code
Ensure appropriate input data present:
CO331 Visual Programming
9
E.g. File searching - Code
Continuing:
Run
CO331 Visual Programming
Hangman
10
Error handling - Exceptions
Is designed to deal with run-time errors such as
• an attempt to divide by zero (integer division)
• where memory becomes exhausted
• an out-of-bounds array index
• arithmetic overflow
Error handling should be used to
• process only exceptional situations
• recover from infrequent fatal errors
• safeguard data and exit a program neatly
• provide some indication of the fault that has arisen
In general program control using conventional control structures is
more efficient than using error handling facilities but the main logic
might become obscured.
CO331 Visual Programming
11
Exceptions – cont’d
Exception is a term used in VB to indicate something has gone wrong.
Exceptions are created by being thrown, and are detected by being
caught. VB uses the keywords Throw, Try and Catch to handle these
operations.
E.g. Try and Catch
Private Sub Calculate_Click(…………….)Handles Calculate.Click
Dim side As Double
Try
side = Double.Parse(txtSide.Text)
lblDisplay.Text = “Area is ” & CStr(side * side) & “ sq units”
Catch exceptionObject As FormatException
lblDisplay.Text = “Error in side: re-enter”
End Try
End Sub
CO331 Visual Programming
12
Exceptions – cont’d
Once an exception has been thrown it is possible to provide
additional information by examining the exception object’s
Message and using theToString Method.
E.g. Catch exceptionObject As FormatException
MessageBox.Show(exceptionObject.Message)
MessageBox.Show(exceptionObject.ToString())
• The message property provides a short string containing a
descriptive error message.
• The ToString method returns a string containing several lines
providing a trace of the actions that led up to the exception
including the location of where the error occurred.
CO331 Visual Programming
13
E.g. Error handling
In the case of division by zero by floating-point division, VB.Net
outputs the word ‘infinity’.
CO331 Visual Programming
14
Files and exceptions
File input-output is a major source of exceptions, e.g.
• incorrect file name
• disk full
• CD removed while reading in progress
The File.OpenText method can throw a number of exceptions. In
particular FileNotFoundException.
E.g. Program 2 may be modified to include
Catch problem As FileNotFoundException
MessageBox.Show(“Error - “ & txtFile.Text & _
“ file not found: . Re-enter name.”)
Catch problem As Exception
MessageBox.Show(“Error – concerning file: “ & _
txtFile.Text & “. “ & problem.message())
End Try
CO331 Visual Programming
15