Lesson 26 of 30 · Files, Errors and Modules
Handling Errors
Stop your Python programs from crashing. Learn try, except, else and finally, how to catch specific errors and how to raise your own.
- 7 min read
- Beginner
- Reviewed
- What an exception is
- How to catch errors with try and except
- How to handle different errors in different ways
- How to raise an error yourself
Errors that happen while the program runs
Some errors cannot be prevented by writing careful code. A user types letters where a number was expected. A file is missing. The internet connection drops. These problems appear while the program is running, and Python reports them as exceptions.
By default, an exception stops the program immediately.
age = int(input("How old are you? "))
print("Next year you will be", age + 1)The user typed twenty, int() could not convert it, and the program stopped with a ValueError. The second line never ran. A real application cannot behave like this.
try and except
Put the risky code in a try block. If an exception happens there, Python jumps to the except block instead of stopping.
try:
age = int(input("How old are you? "))
print("Next year you will be", age + 1)
except ValueError:
print("Please type your age as a number, for example 20.")
print("The program is still running.")Change the input to 20 and run it again. When nothing goes wrong, the except block is skipped.
Catch the specific error
Always name the error you expect. Different problems deserve different responses, and you can add several except blocks.
def divide(a, b):
try:
return a / b
except ZeroDivisionError:
return "Cannot divide by zero"
except TypeError:
return "Both values must be numbers"
print(divide(10, 2))
print(divide(10, 0))
print(divide(10, "two"))These are the exceptions you have met in this course.
| Exception | Cause | Example |
|---|---|---|
ValueError | Right type, wrong value | int("hello") |
TypeError | Wrong type | "age" + 5 |
NameError | Unknown variable name | print(totl) |
IndexError | List position does not exist | items[99] |
KeyError | Dictionary key does not exist | person["email"] |
ZeroDivisionError | Dividing by zero | 10 / 0 |
FileNotFoundError | File does not exist | open("missing.txt") |
Reading the error message
Add as error to get the exception's own message, which is useful to show or record.
try:
with open("missing.txt") as file:
print(file.read())
except FileNotFoundError as error:
print("Could not open the file.")
print("Details:", error)else and finally
Two optional blocks complete the picture.
elseruns only if thetryblock had no error.finallyruns always, error or not. It is used for tidying up.
def read_number(text):
try:
number = int(text)
except ValueError:
print(f"'{text}' is not a number.")
else:
print(f"Got the number {number}.")
finally:
print("Finished checking.")
read_number("42")
read_number("abc")Asking again until the input is valid
Combine try with a while True loop to keep asking until the user gets it right.
while True:
try:
age = int(input("Your age: "))
except ValueError:
print("That is not a number. Try again.")
continue
if age < 0:
print("Age cannot be negative. Try again.")
continue
break
print("Thank you. Age recorded:", age)Raising your own errors
Use raise to signal that something is wrong in your own code. This stops a bad value from travelling further into the program.
def set_price(price):
if price < 0:
raise ValueError("Price cannot be negative")
return price
try:
set_price(-5)
except ValueError as error:
print("Error:", error)Common mistakes
Make safe_divide return a friendly message instead of crashing when the second number is zero.
def safe_divide(a, b):
# Return a / b.
# If b is zero, return the text: Cannot divide by zero
return a / b
# Do not change these two lines. Output must be exactly:
# 5.0
# Cannot divide by zero
print(safe_divide(10, 2))
print(safe_divide(10, 0))When does the code in an except block run?
Summary
- An exception is an error that happens while a program runs.
tryholds the risky code, andexceptsays what to do if it fails.- Name the specific exception:
except ValueError:. elseruns when there was no error, andfinallyalways runs.raisecreates an exception of your own.
Next: using code that other people have already written.
Finished reading? Tick it off to track your progress.