File handling and exception handling

Cambridge IGCSE Computer Science (0478) · lesson 33 of 35 · 25 min

File Handling

Programs often need to read data from files and write results back. Cambridge pseudocode uses the following file operations:

Read all lines from a file and display them

OPENFILE “names.txt” FOR READ

WHILE NOT EOF(“names.txt”) DO

READFILE “names.txt”, line

OUTPUT line

ENDWHILE

CLOSEFILE “names.txt”

Exception Handling

An exception is an unexpected error that occurs during program execution (e.g. dividing by zero, file not found, invalid input). Without handling, exceptions crash the program.

Good programs anticipate exceptions and handle them gracefully — displaying a helpful error message and continuing or exiting cleanly.

In many languages: TRY…EXCEPT…ENDTRY (Python: try/except, Java: try/catch).

Handle division by zero

INPUT a, b

TRY

result ← a / b

OUTPUT result

EXCEPT

OUTPUT “Error: cannot divide by zero”

ENDTRY

Which file mode should you use to add data to the end of an existing file?

  • READ
  • WRITE
  • APPEND
  • UPDATE

Answer: APPEND
APPEND opens the file and positions the write pointer at the end, preserving existing content.

What does EOF() return when the file pointer is at the end of the file?

  • FALSE
  • TRUE
  • 0
  • -1

Answer: TRUE
EOF() returns TRUE when there is no more data to read.

Why should files always be closed after use?

  • To save disk space
  • To release the file resource and ensure data is written
  • To encrypt the file
  • To delete temporary data

Answer: To release the file resource and ensure data is written
Closing a file flushes the write buffer and releases the OS file handle.


Previous lesson: Procedures and functions
Back to Cambridge IGCSE Computer Science (0478)
Next lesson: Logic gates and truth tables