Exception and File Handling in Python

Section B1, Computer Science. Covers Exceptions; try, except, else and finally; Text files; Binary files.

Computer Science/Informatics Practices20 questions4 topics

About this unit

This unit teaches two practical Python skills. The first is exception handling: recognising errors that occur while a program runs and handling them with try, except, else and finally so that the program does not crash. The second is file handling: storing data permanently in text files and binary files, opening files in different modes, reading and writing them, moving the file pointer, and saving Python objects with the pickle module.

Key ideas

  • Syntax errors are found before a program runs; exceptions occur while it runs.
  • Built-in exceptions such as ZeroDivisionError, ValueError, TypeError, IndexError, KeyError, NameError and FileNotFoundError.
  • raise and assert throw exceptions; try … except catches them.
  • else runs when no exception occurs; finally always runs.
  • File modes r, w, a, r+, w+, a+ and their binary forms rb, wb, ab.
  • read(), readline(), readlines(), write(), writelines(), tell() and seek().
  • pickle.dump() and pickle.load() for binary files.

How to prepare

Run small programs yourself and note exactly which exception each mistake produces. Learn a table of file modes in your notebook: whether the file must exist, whether old data is erased, and where the pointer starts. Expect output-prediction questions on try blocks and on read() with tell() and seek().

Topics in this chapter

Practice questions

Practise all 20 questions as a set

Practice this topic