View
213
Download
0
Tags:
Embed Size (px)
Citation preview
1
Lecture
Roger Sutton [email protected]
CO331 Visual Programming
19: Simple file i/o Exceptions – Error handling
CO331 Visual Programming
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.
2
CO331 Visual Programming
File class
Programs that involve file processing must includeImports System.IO
at the beginning.The methods of File class:• OpenText
is used to open an existing fileE.g.
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.
3
File.CreateText (“U:\home\units\co331\aNewFile.txt”)
File.OpenText(“U:\home\units\co331\aOldFile.txt”)
CO331 Visual Programming
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
4
CO331 Visual Programming
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.
5
CO331 Visual Programming
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.
6
CO331 Visual Programming
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, 67Jones, 87, 99Patel, 54, 32Sutton, 65, 74etc…
and we wish to obtain the marks of a particular student from the file and display them.
7
CO331 Visual Programming
File searching - example
The process may be expressed in structured English as:
8
found = FalseWhile (more lines to read) And found = False read line split line into three fields If first field matches name Then
found = Truedisplay other fields in labels
End IfEnd WhileIf Not found Then
display a warningEnd If
CO331 Visual Programming
Error handling - ExceptionsIs 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.
11
CO331 Visual Programming
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
12
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 TryEnd Sub
CO331 Visual Programming
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.
• 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.
13
Catch exceptionObject As FormatException MessageBox.Show(exceptionObject.Message) MessageBox.Show(exceptionObject.ToString())
CO331 Visual Programming
E.g. Error handling
In the case of division by zero by floating-point division, VB.Net outputs the word ‘infinity’.
14
CO331 Visual Programming
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
15
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