Exception and File Handling in Python
Section B1, Computer Science. Covers Exceptions; try, except, else and finally; Text files; Binary files.
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
Exceptions
Syntax errors, built-in and user-defined exceptions; raising and catching them.
5 questionstry, except, else and finally
Handling exceptions and recovering from them.
5 questionsText files
Opening, reading, writing and closing text files; file modes and offsets.
5 questionsBinary files
Reading and writing binary files with the pickle module.
5 questions