Skip to content
Cambridge AS & A Level9618

File Processing and Exception Handling

Computer Science 9618 Chapter Notes

Last updated November 2026

ShareWhatsAppPost

File Processing and Exception Handling notes as a printable PDF.

Read online free. Download a watermarked copy with a free account.

Read the notes

The full File Processing and Exception Handling notes as text: skim, search, and jump between subtopics.

~16 min read

1. Opening and closing a file

A file is opened before it is used and closed when the program has finished with it. The mode says what the program may do: `READ` to read an existing file, `WRITE` for a new file, `APPEND` to add to an existing file and `RANDOM` for a random file.

A file name written in quotes is a literal string. A variable that holds the file name is written without quotes.

``` OPENFILE "Marks.txt" FOR READ OPENFILE "Report.txt" FOR WRITE CLOSEFILE "Marks.txt" CLOSEFILE "Report.txt" ```

Every file opened must be closed. Open each file in the correct mode and close it after the last statement that uses it.

Examiner insight

“Common mistakes included: opening either file in the wrong mode and/or failing to close both files” “A common mistake was to treat the parameter name as a literal string by enclosing it in quotation marks when used in the OPEN and subsequent file operations.”

Worked example 15 marks

The pseudocode algorithm below copies an active accounts text file ActiveFile.txt to an archive accounts text file ArchiveFile.txt, one line at a time. Any blank lines found in the active accounts text file are replaced with the words "Account not present" in the archive accounts text file. Complete this file-handling pseudocode. Parts are missing, marked ........

``` ........ OPENFILE "ArchiveFile.txt" FOR WRITE WHILE NOT ........ READFILE "ActiveFile.txt", Account IF Account = "" THEN WRITEFILE "ArchiveFile.txt", "........" ELSE WRITEFILE "ArchiveFile.txt", ........ ENDIF ENDWHILE ........ CLOSEFILE "ArchiveFile.txt" ```

  1. 1

    Open the file being read, in read mode: `OPENFILE "ActiveFile.txt" FOR READ` [1]

  2. 2

    Loop until the end of the file being read: `WHILE NOT EOF("ActiveFile.txt")` [1]

  3. 3

    Replacement text for a blank line: `WRITEFILE "ArchiveFile.txt", "Account not present"` [1]

  4. 4

    Otherwise copy the line read: `WRITEFILE "ArchiveFile.txt", Account` [1]

  5. 5

    Close the file that was read: `CLOSEFILE "ActiveFile.txt"` [1]

2. Reading and writing lines in a loop

`READFILE` reads the next line of a text file into a variable. `WRITEFILE` writes one line to a file. To process a whole file, loop to EOF with the file name in the brackets.

``` WHILE NOT EOF(OldFile) READFILE OldFile, Line WRITEFILE NewFile, Line ENDWHILE ```

`EOF(file)` gives TRUE or FALSE, so it is never compared with an empty string. Test it on the file being read. To leave out blank lines, skip blank lines with an `IF` before the `WRITEFILE`, and increment a counter when a line is written.

Examiner insight

“A common mistake was to omit the filename from the EOF() function.” “Another mistake was to compare EOF(filename) with an empty string rather than a Boolean value.”

Worked example 17 marks

Each student project is stored in a text file. Each stage of a program creates a new file: MichaelAday_src.txt is the project file produced by student Michael Aday and MichaelAday_S1.txt is the file produced by stage 1. Module DeleteComment() is called with a string representing a line of pseudocode and returns the line after removing any comments.

Module Stage_1() is called with a parameter of type string representing a student name. It creates a new stage 1 file. It copies each line from the student's project file to the stage 1 file after removing any comment from each line. It does not write blank lines to the stage 1 file. It returns the number of lines written to the stage 1 file.

Write pseudocode for module Stage_1(). Module DeleteComment() must be used in your solution.

  1. 1

    Generate the file names from the student name: `OldFile ← StudentName & "_src.txt"` and `NewFile ← StudentName & "_S1.txt"` [1]

  2. 2

    Open both files in the correct modes: `OPENFILE OldFile FOR READ` and `OPENFILE NewFile FOR WRITE`. Close both after the loop with `CLOSEFILE OldFile` and `CLOSEFILE NewFile`. [1]

  3. 3

    Loop to the end of the file being read: `WHILE NOT EOF(OldFile)` [1]

  4. 4

    In the loop, read a line and pass it to the module: `READFILE OldFile, Line` then `Line ← DeleteComment(Line)` [1]

  5. 5

    Skip blank lines after DeleteComment(): `IF LENGTH(Line) <> 0 THEN` [1]

  6. 6

    Write the line to the stage 1 file and increment the count: `WRITEFILE NewFile, Line` then `Count ← Count + 1` [1]

  7. 7

    Return the number of lines after the files are closed: `RETURN Count` [1]

3. Serial, sequential and random files

A serial or sequential file is read from the beginning, one record after another, with `READFILE`. A record is found by searching linearly from the start until it is reached.

A random file is opened `FOR RANDOM`. SEEK moves to a record by its position. GETRECORD then reads the record into a variable, and PUTRECORD writes a variable to the record at that position.

``` OPENFILE "Stock.dat" FOR RANDOM SEEK "Stock.dat", 25 GETRECORD "Stock.dat", Item CLOSEFILE "Stock.dat" ```

A record of a user-defined type is read into one variable. Its fields are written with a dot, such as `Grade.ExamGrade`.

Examiner insight

“A good range of marks was seen, with candidates who described how a record was found by searching linearly from the beginning of the file until the record was found achieving the best marks.”

Worked example 15 marks

The pseudocode algorithm below uses random file access to copy 50 records from a live file CurrentResults.dat to a stored file StoredResults.dat one record at a time. It uses the user-defined type StudentResult. If any grades are missing in CurrentResults.dat, the text "Missing grade" is added to the ExamGrade field in StoredResults.dat. Complete this file handling pseudocode algorithm.

``` DECLARE Grade : StudentResult ........ OPENFILE "StoredResults.dat" FOR RANDOM ........ SEEK "CurrentResults.dat", Position GETRECORD "CurrentResults.dat", Grade IF Grade.ExamGrade = "" THEN ........ ENDIF ........ ........ NEXT Position CLOSEFILE "CurrentResults.dat" CLOSEFILE "StoredResults.dat" ```

  1. 1

    Open the file being read: `OPENFILE "CurrentResults.dat" FOR RANDOM` [1]

  2. 2

    Loop over the 50 records: `FOR Position ← 1 TO 50` [1]

  3. 3

    Put the text in the field: `Grade.ExamGrade ← "Missing grade"` [1]

  4. 4

    Move to the same position in the output file: `SEEK "StoredResults.dat", Position` [1]

  5. 5

    Write the record there: `PUTRECORD "StoredResults.dat", Grade` [1]

4. Finding a record in a random file

To find a record, work out its position, SEEK to it and GETRECORD. Sometimes the position follows from the data. A temperature recorded every minute of the day sits at the number of minutes after midnight, so 10:00 am is position 600 (10 × 60).

Sometimes a hash function gives the position, as in `Location ← Hash(Customer.AccountNumber)`. If neither is available, loop from position 1, adding 1 to `Location` each time, until the record is found or the last location is passed.

A function that returns a value must CLOSEFILE before its `RETURN`. A `RETURN` ends the function, so a `CLOSEFILE` after it never runs.

Examiner insight

“Another error involved solutions that immediately returned TRUE as soon as 10 non-blank lines had been read, which would skip the required CLOSEFILE.”

Worked example 17 marks

A pseudocode algorithm searches for a customer record in a random file AccountRecord.dat. A user inputs the name of the customer. The records are stored using the user-defined data type TAccount, with MaxSize set to 1000. If the record is found, it is output, otherwise an error message is displayed.

Complete the file handling pseudocode.

``` OPENFILE ........ Location ← 1 ........ FALSE ........ WHILE ........ AND Location <= MaxSize ........ "AccountRecord.dat", ........ GETRECORD "AccountRecord.dat", Customer IF SearchCustomer = Customer.Name THEN OUTPUT Customer FoundFlag ← TRUE ENDIF Location ← Location + 1 ENDWHILE IF NOT FoundFlag THEN OUTPUT ........ ENDIF ```

  1. 1

    Open the file: `OPENFILE "AccountRecord.dat" FOR RANDOM` [1]

  2. 2

    Set the flag before the search: `FoundFlag ← FALSE` [1]

  3. 3

    Take in the name to search for: `INPUT SearchCustomer` [1]

  4. 4

    Stop when found: `WHILE NOT FoundFlag AND Location <= MaxSize` [1]

  5. 5

    Move to the record: `SEEK "AccountRecord.dat", Location` [1]

  6. 6

    Give the position held in the loop counter: `Location` [1]

  7. 7

    Report a failed search: `OUTPUT "Customer does not exist."` [1]

5. What an exception is

An exception is an unexpected event that occurs when a program is running. Its effect can be that the program halts unexpectedly.

Causes include programming errors, user errors and hardware failure. Examples are division by zero, a file that is not found, reading past the end of a file and a user typing the wrong file name.

The exception is the event. Responding to it is exception handling, which is the next block.

Examiner insight

“However, some candidates incorrectly described exception handling, which is a remedy for exceptions rather than the exception itself.”

Worked example 15 marks

An exception can occur when running a program.(a) Explain what is meant by an exception.(b) Identify one example of an exception and give one reason why the exception may cause a problem.

  1. 1

    (a) An exception is an unplanned / unexpected event that occurs when a program is running [1]

  2. 2

    ... due to an error in programming or logic that was not detected during program construction or compilation [1]

  3. 3

    The effect of an exception can be that the program halts unexpectedly [1]

  4. 4

    (b) Example: division by zero [1]

  5. 5

    Reason: the processor will not be able to evaluate the answer, so the program will crash [1]

6. Exception handling: why, when and how

Exception handling is the process of responding to an unexpected event when the program is running so that the program does not halt unexpectedly. Use it when a program opens and reads a file, because a file that is not found raises an exception.

The reasons for it are to trap runtime errors, to prevent a program halting unexpectedly and to produce meaningful error messages for these errors.

The code is written as a `TRY ... EXCEPT` pair, which the Paper 4 language writes as `try ... except` or `try ... catch`. The file is opened and closed inside the `TRY`, and the handler outputs a message that describes the error.

``` TRY OPENFILE "Scores.txt" FOR READ WHILE NOT EOF("Scores.txt") READFILE "Scores.txt", Line ENDWHILE CLOSEFILE "Scores.txt" EXCEPT OUTPUT "Scores.txt could not be read" ENDTRY ```

Examiner insight

“A number of candidates incorrectly described the meaning of the term ‘exception’, instead.” “When using exception handling with text files candidates must make sure the opening and closing of the file is within the try clause.”

Worked example 14 marks

State the reasons for including exception handling routines when writing a program. Include an example of an exception in your answer.

  1. 1

    To trap (some) runtime errors [1]

  2. 2

    To prevent a program halting unexpectedly [1]

  3. 3

    To produce meaningful error messages for these errors [1]

  4. 4

    Example of an exception: divide by zero, end of file or file not found [1]

Recap

  • Open a file in the correct mode: `READ`, `WRITE` (new file), `APPEND` (existing file) or `RANDOM`. Close every file you open.
  • File names in quotes are literal strings. A variable holding a file name has no quotes.
  • Process a text file with `WHILE NOT EOF(file)`, `READFILE file, variable` and `WRITEFILE file, data`.
  • Serial and sequential files are read from the start. A random file uses `SEEK`, `GETRECORD` and `PUTRECORD`.
  • Close the file before any `RETURN`, and never inside the reading loop.
  • An exception is an unexpected event during execution that can halt the program.
  • Exception handling responds to it so the program does not halt, using `TRY ... EXCEPT` and a meaningful message, with the file opened and closed inside the `TRY`.

End-of-chapter exercise

Test yourself on the whole chapter. Work through these before moving on.

  1. State the file mode that must be used to add a new line to the end of an existing text file.1 mark
    Answer
    1. `APPEND`.

    Trap: `WRITE` is the mode for a new file, so it is the wrong mode for an existing one; examiners reported the wrong mode.

  2. The variable `FileName` holds the name of a file to be read. A student writes: ``` OPENFILE "FileName" FOR READ ``` Explain the error and write the corrected line.2 marks
    Answer
    1. The quotes make `FileName` a literal string, so the file called FileName is opened, not the file whose name is stored in the variable.
    2. `OPENFILE FileName FOR READ`

    Trap: Quotes are right for a file name typed in the code and wrong for a variable that holds the name.

  3. A loop must repeat until all the lines of Data.txt have been read. A student writes `WHILE NOT EOF`. Explain what is missing and write the corrected line.2 marks
    Answer
    1. `EOF` needs the name of the file it is testing.
    2. `WHILE NOT EOF("Data.txt")`

    Trap: Examiners reported `EOF()` written with the file name left out.

  4. Write pseudocode to output every line of the text file Names.txt.3 marks
    Answer
    1. Open the file for reading: `OPENFILE "Names.txt" FOR READ`
    2. ``` WHILE NOT EOF("Names.txt") READFILE "Names.txt", Line OUTPUT Line ENDWHILE ```
    3. Close the file: `CLOSEFILE "Names.txt"`

    Trap: Leaving out `CLOSEFILE`, or placing it inside the loop.

  5. Write a function `CountLines(FileName : STRING) RETURNS INTEGER`. It reads the text file whose name is in `FileName` and returns the number of lines that are not blank.6 marks
    Answer
    1. ``` FUNCTION CountLines(FileName : STRING) RETURNS INTEGER DECLARE Line : STRING DECLARE Count : INTEGER Count ← 0 OPENFILE FileName FOR READ WHILE NOT EOF(FileName) READFILE FileName, Line IF Line <> "" THEN Count ← Count + 1 ENDIF ENDWHILE CLOSEFILE FileName RETURN Count ENDFUNCTION ```
    2. One mark each: `Count` set to 0, file opened for reading with no quotes round `FileName`, loop to `EOF(FileName)`, line read, count increased only when the line is not blank, file closed before `RETURN Count`.

    Trap: Counting the blank lines instead of the non-blank lines, or returning before the file is closed.

  6. A random file Stock.dat holds one item name in each position. Write the statements that open the file, store the item in position 25 in the variable `Item`, and close the file.3 marks
    Answer
    1. `OPENFILE "Stock.dat" FOR RANDOM`
    2. `SEEK "Stock.dat", 25` then `GETRECORD "Stock.dat", Item`
    3. `CLOSEFILE "Stock.dat"`

    Trap: Using `GETRECORD` without a `SEEK` first, or opening the file `FOR READ`.

  7. Explain the difference between an exception and exception handling.2 marks
    Answer
    1. An exception is an unexpected event that occurs when a program is running and can cause it to halt.
    2. Exception handling is the process of responding to that event so the program does not halt unexpectedly.

    Trap: Defining the event when asked for the process, or the reverse: examiners reported both.

  8. A program asks the user to type the name of a file and then opens it for reading. Give two reasons for including exception handling in this program and name one exception that could occur.3 marks
    Answer
    1. It prevents the program halting unexpectedly if the file cannot be opened.
    2. It produces a meaningful error message for the user.
    3. A file that is not found (for example, the name was typed wrongly).

    Trap: Writing "to stop errors", which is too vague, or describing the exception when asked for the reasons.

  9. A weather station records the rainfall every 15 minutes for one day in the random file Rain.dat. The reading taken at 00:00 is at position 1, the reading at 00:15 is at position 2, and so on. A function `RainAt(Hours : INTEGER, Quarter : INTEGER) RETURNS STRING` is called with the hour (0 to 23) and the quarter of that hour (0 for :00, 1 for :15, 2 for :30, 3 for :45). It returns "Dry" if the reading is 0 and "Wet" otherwise. (a) State the position of the reading taken at 14:45. [1] (b) Write pseudocode for `RainAt()`. [7]8 marks
    Answer
    1. (a) 14 × 4 + 3 + 1 = 56 + 3 + 1 = 60, so the position is 60. Check: 14:45 is 885 minutes after midnight, and 885 ÷ 15 = 59 readings come before it, so it is the 60th.
    2. (b)
    3. ``` FUNCTION RainAt(Hours : INTEGER, Quarter : INTEGER) RETURNS STRING DECLARE Position : INTEGER DECLARE Rain : REAL DECLARE Response : STRING Position ← Hours * 4 + Quarter + 1 OPENFILE "Rain.dat" FOR RANDOM SEEK "Rain.dat", Position GETRECORD "Rain.dat", Rain IF Rain = 0 THEN Response ← "Dry" ELSE Response ← "Wet" ENDIF CLOSEFILE "Rain.dat" RETURN Response ENDFUNCTION ```
    4. One mark each: function header with both parameters and `RETURNS STRING`, position calculated with the +1, file opened `FOR RANDOM`, `SEEK` to the position, `GETRECORD` into a variable, `IF ... ELSE` giving "Dry" or "Wet", `CLOSEFILE` before the one `RETURN`.

    Trap: Writing `RETURN "Dry"` inside the `IF`, which ends the function before `CLOSEFILE` runs, as examiners reported; also leaving out the +1 because 00:00 is at position 1, not 0.

  10. A text file holds one whole-number score on each line, but some lines are blank. Write pseudocode that asks the user to enter the file name, reads the file and outputs the mean of the scores. Blank lines are ignored. If no line holds a score, output "No scores". If the file cannot be opened, the program must output a message and must not halt. Use `STR_TO_NUM(Line)` to convert a line to a number.8 marks
    Answer
    1. ``` DECLARE FileName, Line : STRING DECLARE Total, Count : INTEGER Total ← 0 Count ← 0 OUTPUT "Enter the file name" INPUT FileName TRY OPENFILE FileName FOR READ WHILE NOT EOF(FileName) READFILE FileName, Line IF Line <> "" THEN Total ← Total + STR_TO_NUM(Line) Count ← Count + 1 ENDIF ENDWHILE CLOSEFILE FileName IF Count > 0 THEN OUTPUT "Mean is ", Total / Count ELSE OUTPUT "No scores" ENDIF EXCEPT OUTPUT "The file could not be read" ENDTRY ```
    2. One mark each: name input into a variable, file opened for reading using the variable with no quotes, loop to `EOF(FileName)` reading a line, blank lines skipped, each score converted and added with `Count` increased, `CLOSEFILE` after the loop and inside the `TRY`, mean output only when `Count > 0`, `TRY ... EXCEPT` round the file handling with a message in the handler.

    Trap: Placing the open outside the `TRY` or the close inside the loop, as examiners reported, or dividing by `Count` when it is 0, which is itself a division-by-zero exception.

Say this, not that

Wording that loses the mark, against the wording the mark scheme credits.

Loses the markGets the mark
`OPENFILE "FileName" FOR READ` when `FileName` is a variable`OPENFILE FileName FOR READ`, with no quotes round a variable
`WHILE NOT EOF` with no file name`WHILE NOT EOF(FileName)`, loop to EOF of the file being read
An exception is responding to an error so the program does not stop.An exception is an unexpected event that occurs when a program is running.
Exception handling is an error that stops the program.Exception handling is responding to an unexpected event so the program does not halt unexpectedly.

Frequently asked questions

How do you open and close a file in pseudocode?
A file is opened before it is used and closed when the program has finished with it. The mode says what the program may do: READ for an existing file, WRITE for a new file, APPEND to add to an existing file, and RANDOM for a random file. Every file opened must be closed, after the last statement that uses it.
How do you read a text file line by line until the end?
Loop to EOF with the file name in the brackets, as WHILE NOT EOF(OldFile). Inside the loop, READFILE reads the next line of the file into a variable, and WRITEFILE writes one line to a file. EOF(file) gives TRUE or FALSE, so it is never compared with an empty string.
How do you find and read a record in a random file?
Work out the position of the record, then use SEEK to move to it. GETRECORD reads the record into a variable, and PUTRECORD writes a variable to the record at that position. Sometimes the position follows from the data, and sometimes a hash function gives it. A function must CLOSEFILE before its RETURN.
What is an exception in a program?
An exception is an unexpected event that occurs when a program is running. Its effect can be that the program halts unexpectedly. Causes include programming errors, user errors and hardware failure. Examples are division by zero, a file that is not found, reading past the end of a file and a user typing the wrong file name.
What is exception handling and why is it used?
Exception handling is the process of responding to an unexpected event when the program is running, so that the program does not halt unexpectedly. Its reasons are to trap runtime errors, to prevent a program halting unexpectedly and to produce meaningful error messages. The file is opened and closed inside the TRY, and the EXCEPT part outputs the message.
Why is OPENFILE "FileName" wrong when FileName is a variable?
Quotes make FileName a literal string, so the file called FileName is opened rather than the file whose name is stored in the variable. Write OPENFILE FileName FOR READ with no quotes round a variable. Quotes are right only for a file name typed in the code.

Free notes are just the start.

Unlock every Workbook and Chapter at a Glance, and generate your own worksheets and predicted papers.

Explore plans

Related chapters