Error handling
- Python course
- Beginner
- Lesson 22/116
- 6 min
Catch invalid inputs with try/except.
Catching errors with try/except
In this lesson we'll introduce the try/except structure. It catches an error and prevents the program from crashing:
try:
result = 10 / 0
except ZeroDivisionError:
result = 0If the code in the try block raises an error, Python jumps to the except block. If the error type matches ZeroDivisionError, that block runs.
We'll cover try/except in detail in a separate group. Here we'll use it to safely catch division errors.
Safe division
Now we'll make the divide function safe with try/except. If the divisor is zero, we'll catch the error and return 0:
def divide(x, y):
try:
return x / y
except ZeroDivisionError:
return 0This approach is considered more Pythonic than an if check: let the error happen and catch it.
This follows the "easier to ask forgiveness than permission" philosophy.
Practice Add safe divide
The previous functions are ready. Rewrite the divide function with try/except: try: return x / y, except ZeroDivisionError: return 0. Then print print(divide(a, b)) and print(divide(a, 0)).
Starter code
# Calculator - define two numbers
a = 10
b = 5
print(a, b)
def add(x, y):
return x + y
def subtract(x, y):
return x - y
def multiply(x, y):
return x * y
print(add(a, b))
print(subtract(a, b))
print(multiply(a, b))
# Add the safe divide functionSample solution
def divide(x, y):
try:
return x / y
except ZeroDivisionError:
return 0
print(divide(a, b))
print(divide(a, 0))Expected output
10 5 15 5 50 2.0 0
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the except block
try:
result = 10 / 0
____ ZeroDivisionError:
result = 0
try:
result = 10 / 0
except ZeroDivisionError:
result = 0
Explanation: except catches the error type.
2 What happens if an error occurs in the try block?
- The program crashes
- The error is ignored
- The try block runs again
- The except block runs Correct answer
Explanation: If an error occurs, the except block runs.
3 Match the error handling concepts
| Term | Meaning |
|---|---|
try |
Code to try |
except |
Error catching |
ZeroDivisionError |
Division error |
return 0 |
Value after error |