5) Exceptions Lesson

Try to Avoid Python Exceptions

3 min to complete · By Martin Breuss

The Python community has been called out for overusing exceptions as control flow statements.

Handle Python Exceptions Differently

For example, sometimes you may see exceptions used for expected errors that could be handled differently:

animals_of_africa = {
    "aardvark": "a nocturnal badger-sized burrowing mammal",
    "zebra": "a wild horse with black-and-white stripes"
    }

animal = input("Animal to look up: ")

try:
    print(animals_of_africa[animal])
except KeyError:
    print("This animal is not in the database")

In this example, you used a try except statement to catch a KeyError. Python raises a KeyError when you attempt a dictionary lookup using square bracket syntax on a key that doesn't exist in the dictionary.

Use the Dictionary Get

The code snippet works, but there are more idiomatic ways to handle the situation in Python: use the dictionary method .get():

animals_of_africa = {
    "aardvark": "a nocturnal badger-sized burrowing mammal",
    "zebra": "a wild horse with black-and-white stripes"
    }

animal = input("Animal to look up: ")

print(animals_of_africa.get(animal, "This animal is not in the database"))

In the code example above, you used .get() to retrieve the values from your dictionary. The method will return a default value when the key isn't found in the dictionary.

When you consider the code example at the beginning of this page, then you may notice that you'll always catch a KeyError that might come up. You'll never let the exception bubble up and end your script run. Therefore, you should prefer using the more idiomatic approach with .get() in such a situation, which avoids raising an exception but provides the same functionality.

There are similar examples you may encounter. Try to look for an idiomatic approach before resorting to overusing exceptions as control flow in your code.

Summary: When to Avoid Python Exceptions

  • Python exceptions can be overused
  • Avoid using exceptions if other idiomatic structures in the language are more concise and more descriptive