What an exception is
When Python cannot carry on, it raises an exception: an object that describes what went wrong. If nothing catches it, the program stops and prints a traceback.
int("twelve") # ValueError: invalid literal for int()
10 / 0 # ZeroDivisionError: division by zero
[1, 2, 3][5] # IndexError: list index out of range
{"a": 1}["b"] # KeyError: 'b'
The debugging tutorial explains how to read a traceback. This tutorial is about responding to errors you expect.
try and except
def to_number(text):
try:
return int(text)
except ValueError:
print(f"'{text}' is not a whole number")
return None
print(to_number("42"))
print(to_number("forty-two"))
Python runs the try block. If a ValueError happens, it jumps to the matching except block instead of crashing. Always name the exception you expect. A bare except: also catches typos and other bugs, which makes them very hard to find.
Several errors, else and finally
def safe_divide(a, b):
try:
result = a / b
except ZeroDivisionError:
print("Cannot divide by zero")
except TypeError:
print("Both values must be numbers")
else:
print("Result:", result)
finally:
print("Done")
safe_divide(10, 4)
safe_divide(10, 0)
safe_divide(10, "2")
elseruns only when no exception happened.finallyalways runs, error or not. It is the place for clean-up such as closing a connection.
Raising your own errors
Your own functions should refuse bad input loudly, with a message that says what is wrong:
def set_grade(score):
if not 0 <= score <= 100:
raise ValueError(f"score must be between 0 and 100, got {score}")
return "pass" if score >= 50 else "fail"
for value in [75, 30, 120]:
try:
print(value, set_grade(value))
except ValueError as error:
print("Problem:", error)
except ValueError as error stores the exception in a variable so you can show its message.
Files and with
try:
with open("settings.txt") as f:
settings = f.read()
except FileNotFoundError:
settings = "theme=light"
print("No settings file yet, using defaults")
print(settings)
The with statement closes the file automatically, even if an error happens while reading. Handle the specific case you can fix (a missing file) and let anything unexpected stop the program, so you notice it.
Try it yourself
In Unays Code, write a function average(numbers) that raises a ValueError with a clear message when the list is empty, then call it inside try and print the message. Next, combine this with the input loop from your first Python program.
This tutorial was written with AI assistance and reviewed by Unays. The runnable code examples were tested before publishing. Spotted a mistake? Tell us at [email protected].