When something goes wrong while a program runs, Python raises an exception: it stops what it's doing and, unless something catches it, prints a traceback and ends. A traceback lists the calls that led to the problem, oldest first, with the file and line of each. Read it from the bottom: the last line has the exception's type and message, and the line above it is where it happened.
Traceback (most recent call last):
File "shop.py", line 7, in <module>
print(average([]))
File "shop.py", line 2, in average
return sum(nums) / len(nums)
ZeroDivisionError: division by zero
Here average divided by len([]), which is 0. The common types are worth knowing by name: ValueError (right type, bad value), TypeError (wrong type), KeyError and IndexError (missing key or position), ZeroDivisionError, FileNotFoundError and AttributeError (no such method or attribute on that value).
To handle an error instead of crashing, put the risky code in a try block and the recovery in an except block naming the exception. If the try block raises that exception, Python jumps to except; if not, except is skipped.
Catch the specific exceptions you expect. A bare except: (or except Exception:) also swallows mistakes you didn't expect, like a typo in a variable name, which makes bugs very hard to find. except ValueError as e: gives you the exception so you can print its message.
else runs only if no exception happened, and finally runs no matter what, even after a return. finally is for cleanup, like closing a connection.
def divide(a, b):
try:
result = a / b
except ZeroDivisionError as e:
print("Error:", e)
return None
else:
return result
finally:
print("checked", a, b)
print(divide(6, 3))
print(divide(1, 0))
Prints
checked 6 3
2.0
Error: division by zero
checked 1 0
None
You can raise exceptions yourself with raise, when your function is given something it can't work with. It's better to fail loudly and early with a clear message than to carry on with bad data.
def set_age(age):
if age < 0:
raise ValueError(f"age can't be negative: {age}")
return age
try:
set_age(-3)
except ValueError as e:
print(e)
Prints
age can't be negative: -3
Practice
Which line of this traceback names the kind of error?
A traceback
More info
Quick reference
traceback
The error report. Read the last line first: type and message.
try: ... except X:
Run the code; if it raises X, run the except block instead of crashing.