File Processing and Exception Handling

Computer Science A2 · Further Programming. The idea in plain words, the rules to remember, the mistake to avoid and a worked example, written and checked by Mega Lecture.

Test this topic freeAll Computer Science A2 topics

The idea

A file keeps data after the program ends. A file must be opened in a mode before use and closed afterwards. Read mode reads existing data. Write mode makes a new file, and deletes the old contents if the file already exists. Append mode adds data to the end.

A serial file stores records in the order they arrive. A sequential file keeps them in key order. Both are read from the start. A random (direct access) file lets the program go straight to a record at a given position.

An exception is an unexpected event at run time, such as a missing file or division by zero. Exception handling catches it so the program does not crash.

Rules to remember

Common mistake

Students open an existing file in write mode to add a record, which wipes everything already in it. Use append mode to add to the end, and remember that read mode on a missing file raises an exception.

Worked example

Temps.txt holds 15, 22, 9, 30 and 18, one on each line. Count ← 0, then the file is opened FOR READ and a WHILE NOT EOF loop does READFILE "Temps.txt", Line and adds 1 to Count IF STR_TO_NUM(Line) > 16. What is Count at the end?

  1. 15 is not greater than 16, so Count stays 0. 22 is greater, so Count = 1.
  2. 9 is not greater, so Count stays 1. 30 is greater, so Count = 2.
  3. 18 is greater, so Count = 3. EOF is now TRUE, so the loop ends and the file is closed.

Answer: Count = 3.

Ask about this

Type what you are stuck on. The helper finds the explanation, worked examples and the notes to read, free and instant.

Keep going

← Programming ParadigmsTake a Computer Science A2 test