Specialty Digest

Global English editionLearners’ Study Dashboard — in development
The Knowledge Library for All

Flashcards: open the module flashcards (end-of-module review with workplace questions).

Online Courses / University Track / Python from Zero

Module 7 · Lesson 2 · Core

Handling errors with try and except

Catch an expected error, handle it, and avoid hiding problems.

  • 50 minutes
  • Serves O5
  • Assumes M7.L1

Phase 1: Prepare

Step 1 Warm-up recall

From M7.L1: which error does int("abc") cause?

Private: nothing you type here is sent or stored.

Step 2 Learning goal

By the end of this lesson you can:

  • write try and except for a named error (Foundation);
  • choose a safe response (Core);
  • avoid hiding faults (Core).

Phase 2: Teach

Step 3 A familiar example

A cashier keys a price. If the entry is not a number, she asks again rather than closing the till. try and except lets a program do the same.

Step 4 Clear explanation

Some failures are expected: a user types text where a number is needed, or a file is missing. try runs the risky step; except says what to do if a named error occurs.

text = "abc"
try:
    qty = int(text)
    print("Quantity", qty)
except ValueError:
    print("Please enter a whole number")
print("Program continues")
Please enter a whole number
Program continues
tryrisky stepexceptnamed errorContinuesafely
try runs the risky step. If a named error happens, except handles it and the program carries on.

Always name the error you expect. A bare except: catches every error, including your own mistakes, and hides them. That turns a program that stops loudly into one that quietly gives wrong answers.

A good response does one of four things: ask again, use a safe default, skip and report, or stop with a clear message. Do not simply say nothing. In Module 6 a bad row was counted and reported; here the same idea is applied through an exception.

Step 5 Worked example (4 marks)

Predict the output of try: n = int("7"); print(10 / n) except ZeroDivisionError: print("zero"), then of the same program with "0" in place of "7".

  1. With "7": n is 7 and 10 / 7 is printed as about 1.43. (1 mark)
  2. With "0": int works and n is 0. (1 mark)
  3. 10 / 0 raises ZeroDivisionError, which is caught, so zero is printed. (1 mark)
  4. Answer: 1.428..., then zero. (1 mark)

Go deeper: the professor's notes

Plan for failure: handle what you expect and make the rest fail clearly, not silently.
Expect

Name the error.

Respond

Ask or report.

Never

Hide it.

tryrisky stepexceptnamed errorReportclearlyContinuesafely
Handle it

Responses

ResponseGood?
report and continueyes
say nothingno

At work: A bad entry

A user types text for a quantity.

  1. Catch ValueError.
  2. Ask again.

What a careful practitioner decides. Handle expected failures; do not hide mistakes.

Phase 3: Practise

Step 6 Learner practice (instant-marked)

1. Code that might fail goes in:

2. except ValueError catches:

3. A bare except: is risky because it:

4. A good response to an expected error is to:

Phase 4: Close

Step 7 Recap

  • try runs the risky step; except handles a named error.
  • Name the error; never use a bare except.
  • Respond clearly: ask again, default, report or stop.

Step 8 Exit ticket (ungraded)

Write try and except so that a text entry such as "x" for a quantity prints a message instead of stopping.

Private: nothing you type here is sent or stored.

Step 9 Go further (Extension)

Write a loop that keeps asking for a whole number until the user gives one.

In industry: Therac-25: reused software, unseen link

The quality assurance manager at the manufacturer was apparently unaware that some Therac-20 routines were also used in the Therac-25. A bug linked to one of the accidents was later found in the Therac-20 software.

Link to this lesson. Reused code carries its old faults with it; know where each piece of your program came from and test it again in the new setting.

Source: Leveson and Turner, IEEE Computer (July 1993)

Common mistakes

MistakeWhy it fails
A bare exceptName the error you expect.
Handling an error and saying nothingReport it or count it.
Putting too much code inside tryKeep the risky step small.

Limits. This lesson does not cover else, finally or raising your own errors, which are useful in larger programs.

Flashcards for this lesson (3)

Tap a card to reveal the answer. Read the question, answer it aloud or in writing first, then check yourself against the explanation.

Card 1 of 3 · What is a TypeError or a ValueError?
Typewrong kindValuebad contentFixconvert or check
Type and Value

TypeError: the wrong kind of value, such as adding text to a number. ValueError: the right kind but unusable, such as int("abc").

Card 2 of 3 · What are IndexError and KeyError?
ListIndexErrorDictKeyErrorChecklen or in
Index and Key

IndexError: a list position that does not exist. KeyError: a dictionary key that is not present. Check with len or in before using it.

Card 3 of 3 · Why is a wrong answer with no error the worst fault?
Runsno errorResultwrongFindby testing
Silent fault

Nothing warns you, so the wrong total is used. Only testing against a known answer reveals it. Check results as well as crashes.

Review with flashcards

Test yourself on this module with workplace flashcards and detailed answers.

Open the module flashcards