Python for beginners · Lesson 13 of 15
Errors and exceptions
Read Python's error messages, know the common error types, catch problems with try and except, and raise errors with your own messages.
Every programmer sees errors every day, so learning to read them is one of the most useful skills you can have. When Python cannot continue, it stops and prints a traceback: a report that shows where things went wrong.
Read a traceback from the bottom up. The last line names the error type (such as ValueError), followed by a colon and a short description. The lines above it show the file and line number, and the code on that line. The exact wording of the description can change between Python versions, but the error type stays the same.
SyntaxError: the code is not valid Python, for example a missing colon or bracket. Nothing runs at all.IndentationError: the indentation of a block is wrong.NameError: you used a name that does not exist, often a typo liketotlinstead oftotal.TypeError: an operation got the wrong kind of value, for example"5" + 3.ValueError: the kind of value is right but the value itself is not, for exampleint("ten").ZeroDivisionError: dividing by zero.IndexErrorandKeyError: a list position or dictionary key that does not exist.FileNotFoundError: opening a file that is not there.
Catching errors with try and except
When you expect that something might fail, put it in a try / except / else / finally block. If an error of the type named after except happens, Python jumps to the except block instead of stopping, and the program carries on.
text = "abc"
try:
number = int(text)
print("You typed", number)
except ValueError:
print("That is not a whole number.")
print("The program keeps running.")That is not a whole number. The program keeps running.
The line after int(text) is skipped, because the error happened first.
except ValueError as error: stores the error in a variable. type(error).__name__ gives you the name of its type, which is handy when you want to report what went wrong without depending on Python's exact wording.
values = ["12", "4.5", "seven"]
for v in values:
try:
print(int(v) * 2)
except ValueError as error:
print(type(error).__name__, "for", v)24 ValueError for 4.5 ValueError for seven
Several kinds of errors
A try can have several except blocks, one for each kind of error you want to handle differently.
def divide(a, b):
try:
return a / b
except ZeroDivisionError:
print("Cannot divide by zero.")
except TypeError:
print("Both values must be numbers.")
print(divide(10, 4))
print(divide(10, 0))
print(divide(10, "2"))2.5 Cannot divide by zero. None Both values must be numbers. None
After an except block the function ends without return, so it gives back None.
while True:
try:
age = int(input("Age: "))
break
except ValueError:
print("Please type digits only.")
print("Next year you will be", age + 1)Age: Please type digits only. Age: Next year you will be 13
With a while loop, try keeps asking until the answer is valid. Typed answers: twelve, 12
else, finally and raising your own errors
An else block runs only when no error happened, and a finally block runs in every case. With raise you create an error yourself, with your own message, when your function gets a value it cannot accept.
def set_age(age):
if age < 0:
raise ValueError("age cannot be negative")
return age
for value in [30, -5]:
try:
age = set_age(value)
except ValueError as error:
print("Error:", error)
else:
print("Age saved:", age)
finally:
print("Checked", value)Age saved: 30 Checked 30 Error: age cannot be negative Checked -5
except: with no error type. It also catches mistakes you did not expect, such as a typo in a variable name, and hides them. Name the error types you mean to handle.✎ Exercise
Write a function to_number(text) that returns the text as a float, or None when it cannot be converted. Test it with the loop below.
Hint: Put return float(text) inside try, and return None in the except ValueError block.
def to_number(text):
# your code here
return None
for t in ["3.5", "abc", "10"]:
print(t, "->", to_number(t))
Expected output:
3.5 -> 3.5 abc -> None 10 -> 10.0
Show a solution
def to_number(text):
try:
return float(text)
except ValueError:
return None
for t in ["3.5", "abc", "10"]:
print(t, "->", to_number(t))3.5 -> 3.5 abc -> None 10 -> 10.0
Check yourself
1. Which error does int("hello") raise?
The argument is a string, which int() accepts, but this particular string is not a number: that is a ValueError.
2. Where should you start reading a traceback?
The last line names the error type and describes the problem. The lines above show where it happened.
3. When does a finally block run?
finally runs in every case, which makes it the place for clean-up work.