Skip to ContentGo to accessibility pageKeyboard shortcuts menu
OpenStax Logo
Introduction to Python Programming

14.5 Raising exceptions

Introduction to Python Programming14.5 Raising exceptions

Learning objectives

By the end of this section you should be able to

  • Use a raise statement to indicate that user input is invalid.
  • Explain the flow of execution when an exception is raised.

The raise statement

A program can raise an exception when an error is detected. Raising an exception forces a program to deal with the error. If the exception is not handled using try and except, the program displays an error message and terminates.

Example 14.6

Invalid pizza size

The following class represents a pizza for sale. The SIZES dictionary maps an abbreviation to a size's name and price. Line 11 checks if the size received by the constructor is in the dictionary. Line 12 raises a ValueError with specific error message.

class Pizza:
    SIZES = {
        "S": ("Small", 5.99),
        "M": ("Medium", 7.99),
        "L": ("Large", 9.99),
        "XL": ("X-Large", 11.99),
    def __init__(self, size):
        if size not in Pizza.SIZES:
          raise ValueError(f"Unknown size '{size}'")
        self.size = size
    def __str__(self):
        name, price = Pizza.SIZES[self.size]
        return f"{name} pizza for ${price}"
if __name__ == "__main__":
    p1 = Pizza("L")
    p2 = Pizza("Z")
    Large pizza for $9.99
    Traceback (most recent call last):
      File "", line 23, in <module>
        p2 = Pizza("Z")
      File "", line 12, in __init__
        raise ValueError(f"Unknown size '{size}'")
    ValueError: Unknown size 'Z'

Raising an exception in a constructor prevents an invalid object from being constructed. In the example, p1 is constructed but p2 is not constructed.

Concepts in Practice

Predicting output with raise

For each code snippet, what is the output?

p3 = Pizza("M")
  1. Medium pizza for $7.99
  2. ValueError: Unknown size 'M'
  3. TypeError: missing argument
raise PizzaError("Invalid size")
  1. Invalid size
  2. PizzaError: Invalid size
  3. NameError: name 'PizzaError' is not defined
raise ValueError
  1. ValueError
  2. NameError: name 'ValueError' is not defined
  3. SyntaxError: Missing parenthesis in call to 'ValueError'

Try It

Language objects

The file top27.csv is based on Wikipedia's list of languages by number of native speakers. A linguist would like to work with this data in an object-oriented way and has already defined a Language class. However, the code is not working correctly because of errors in the CSV file. (The CSV program cannot be changed because the program's purpose is to detect these kinds of errors.)

Your task is to modify the constructor to raise a ValueError in the following situations:

  • If the line does not have exactly four values (separated by commas).
  • If the number of speakers is not a positive floating point number.

Note: The provided top27.csv includes mistakes for English, Korean, and French. Your program should raise a ValueError only for these languages. No other errors (including IndexError) should be raised.

Try It

Looking up keys

When looking up a value in a dictionary, a key has to match exactly. Ex: Given fruit = {"apple": 1, "banana": 2}, the expression fruit["Apple"] raises a KeyError because "Apple" is not the same as "apple". Likewise, fruit["NANA"] raises a KeyError because "nana" does not exactly match "banana".

Implement the lookup() function. This function tries to find a key in the dictionary that matches the search term. A key matches if the search term is a substring of the key, ignoring case. Ex: The key "banana" matches the search term "NANA".

If no matching keys are found, lookup() should raise a KeyError with the message "search term not found". If multiple matches are found, lookup() should raise a KeyError with the message "multiple keys found". Otherwise, lookup() should return both the key and the value for the matching item in the dictionary.

Given the books.csv file, the output should be:

    Found: ('Pride and Prejudice', 9780141439518)
    Found: ('The Hobbit', 9780547928227)
    Error: search term not found
    Error: multiple keys found

This book may not be used in the training of large language models or otherwise be ingested into large language models or generative AI offerings without OpenStax's permission.

Want to cite, share, or modify this book? This book uses the Creative Commons Attribution License and you must attribute OpenStax.

Attribution information
  • If you are redistributing all or part of this book in a print format, then you must include on every physical page the following attribution:
    Access for free at
  • If you are redistributing all or part of this book in a digital format, then you must include on every digital page view the following attribution:
    Access for free at
Citation information

© Feb 26, 2024 OpenStax. Textbook content produced by OpenStax is licensed under a Creative Commons Attribution License . The OpenStax name, OpenStax logo, OpenStax book covers, OpenStax CNX name, and OpenStax CNX logo are not subject to the Creative Commons license and may not be reproduced without the prior and express written consent of Rice University.