Python Catching the Right Exception
A named except catches one error type. A bare except catches every error type.
Catch a missing key by name
The key Bob is missing. The named except prints a plain line.
ages = {"Ada": 30}
try:
print(ages["Bob"])
except KeyError:
print("No age for Bob")Catch a bad value by name
The text abc is not a number. The named except prints a plain line.
try:
print(int("abc"))
except ValueError:
print("Not a number")A bare except hides a slip
The name agse is a slip for ages. The bare except blames the key instead.
ages = {"Ada": 30}
try:
print(agse["Ada"])
except:
print("Not found")One handler per error type
Each except names its own error. Each block prints its own plain line.
scores = {"Ada": 88}
try:
print(scores["Bob"])
except KeyError:
print("No score")
try:
print(int("abc"))
except ValueError:
print("Bad score")Example
def show_age(people, name):
try:
print(name, people[name])
except KeyError:
print(name, "is not listed")
def show_score(text):
try:
print("Score:", int(text))
except ValueError:
print(text, "is not a score")
people = {"Ada": 30, "Cy": 25}
show_age(people, "Ada")
show_age(people, "Bob")
show_score("42")
show_score("high")
print("Done")Key points
- Named except: an except line that names one error type
- Use except KeyError to catch a missing dict key
- Use except ValueError to catch a bad value
- A bare except has no error name after except
- A bare except also catches a typing slip in the try block
- A caught error lets the program carry on
In this example, people holds two ages. show_age prints Ada with her age. Bob is not listed, so the KeyError block runs. show_score turns 42 into a number. The text high is not a score, so the ValueError block runs. The last line prints Done, so both handlers let the program carry on.
Note
Catch the error you expect, not every error.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Python Playground
Exercise
A try block holds a misspelled name. A bare except prints "Not found". What happened?