After this lesson you will be able to stop a program from crashing on bad input, and decide what it should do instead. This is the everyday tool for dealing with the exceptions you met in the previous lesson.
The basic shape
Put the risky code in a try block. If it raises an exception, Python skips the rest of that block and runs the matching except block. If nothing goes wrong, the except block is skipped.
def to_quantity(text):
try:
return int(text)
except ValueError:
return 0
print(to_quantity("12"))
print(to_quantity("twelve"))
print(to_quantity(""))12
0
0Notice that the program keeps going. Without the try, the second call would have stopped everything with a traceback.
Catch the specific error
Always name the exception you expect. Here a shop works out the price of one item from a total and a count. Two different things can go wrong, and each deserves its own reaction.
def unit_price(total, count):
try:
return round(float(total) / int(count), 2)
except ValueError:
return "Please enter numbers only"
except ZeroDivisionError:
return "Count cannot be zero"
print(unit_price("50", "4"))
print(unit_price("fifty", "4"))
print(unit_price("50", "0"))12.5
Please enter numbers only
Count cannot be zeroPython checks the except clauses from top to bottom and runs the first one that matches. To treat several types the same way, put them in a tuple:
def first_word(items, index):
try:
return items[index]
except (IndexError, KeyError):
return "not found"
print(first_word(["pen", "ink"], 1))
print(first_word(["pen", "ink"], 7))
print(first_word({"a": "apple"}, "b"))ink
not found
not foundReading the error with as
Add as name to get the exception object. Printing it shows the message Python would have put at the bottom of a traceback.
try:
int("4.5")
except ValueError as err:
print("Could not convert:", err)
print(type(err).__name__)Could not convert: invalid literal for int() with base 10: '4.5'
ValueErrorelse: the success path
An optional else block runs only if the try block finished without raising anything. It keeps the risky line on its own, so you do not accidentally catch errors from the code that follows.
def parse_age(text):
try:
age = int(text)
except ValueError:
print("Not a number:", text)
else:
print("Age accepted:", age)
parse_age("17")
parse_age("seventeen")Age accepted: 17
Not a number: seventeenfinally: always run
A finally block runs no matter what: after success, after a caught error, and even after a return. Use it for clean-up that must happen every time.
def check_stock(stock, item):
try:
return stock[item]
except KeyError:
return -1
finally:
print("Checked", item)
stock = {"pens": 40}
print(check_stock(stock, "pens"))
print(check_stock(stock, "ink"))Checked pens
40
Checked ink
-1The word Checked is printed before each result, because finally runs before the function hands back its value. In a later lesson you will see that the with statement handles most clean-up jobs more neatly.
All four together
def divide(a, b):
try:
result = a / b
except ZeroDivisionError:
print("Cannot divide by zero")
return None
else:
print("Division worked")
return result
finally:
print("Done")
print(divide(10, 4))
print(divide(1, 0))Division worked
Done
2.5
Cannot divide by zero
Done
NoneWhen to catch, and when not to
Catching an exception is a promise that you know what to do about it. Good reasons: asking the user to type again, using a default value, skipping a bad row, or showing a friendly message. A poor reason is silencing an error you do not understand. If the right response is "nothing sensible can be done here", let the exception travel up so a caller, or the user, can see it.
A related point is the difference between asking permission and asking forgiveness. You can check first (if "ink" in stock) or try first and catch the KeyError. Both are fine. Checking reads better when failure is common, and try suits cases where the failure is rare or where checking and acting could be separated by something else changing, such as a file being deleted.
Common mistakes
- A bare
except:. It catches nearly everything, including typos in your own code, and makes real bugs invisible. Name the type. - Putting too much inside
try. Keep the block small. If twenty lines are inside, you cannot tell which one failed. - Catching and doing nothing.
except ValueError: passthrows the error away. At least print or log a message so you know it happened. - Wrong order of clauses. A parent type placed first catches the children, and the specific clause below it never runs. Put the narrow types first.
- Expecting
tryto fix a syntax error. A syntax error stops Python before the program starts, sotrynever gets the chance to help.
Exercise
Write a function safe_ratio(a, b) that returns a / b. If b is zero it returns None. If either value cannot be turned into a number, it returns the text "bad input". Test it with ("9", "3"), ("9", "0") and ("nine", "3").
Show one possible answer
def safe_ratio(a, b):
try:
return float(a) / float(b)
except ZeroDivisionError:
return None
except ValueError:
return "bad input"
print(safe_ratio("9", "3"))
print(safe_ratio("9", "0"))
print(safe_ratio("nine", "3"))3.0
None
bad inputNext: raising and defining exceptions shows how to signal errors from your own code. A video version of this topic is in the video course at /learn/python/.
Key points
- try runs risky code. If an exception happens, Python jumps to the matching except block instead of stopping the program.
- Catch specific exceptions such as ValueError. A bare except hides real bugs.
- else runs only when the try block raised nothing, and finally runs every time, even after a return.
- Use as to get the exception object and read its message.
- Only catch an error when you know a sensible way to deal with it.