Lesson 1 of 5 · Errors and Files · 3 min read · Updated
Handling errors with try and except
Catching an error so the program can recover instead of crashing.
When something goes wrong at run time, Python raises an exception. Unhandled, it stops the program with a traceback. Wrapped in try, you decide what happens instead.
values = ["42", "abc", "7"]
for text in values:
try:
number = int(text)
print(number * 2)
except ValueError:
print(f"'{text}' is not a number")
84
'abc' is not a number
14
The bad value was handled and the loop carried on to the next one. Name the exception you expect — here ValueError, which is what int() raises for text that is not a number.
else, finally and several excepts
def safe_divide(a, b):
try:
result = a / b
except ZeroDivisionError:
return "Cannot divide by zero"
except TypeError as e:
return f"Bad input: {e}"
else:
return result
finally:
print("checked", a, b)
print(safe_divide(10, 2))
print(safe_divide(1, 0))
print(safe_divide("1", 2))
checked 10 2
5.0
checked 1 0
Cannot divide by zero
checked 1 2
Bad input: unsupported operand type(s) for /: 'str' and 'int'
- Each
excepthandles one kind of error; the first that matches runs. as ekeeps the exception, so you can show its message.elseruns only if nothing went wrong.finallyruns no matter what — even after a return. Use it for clean-up.
Asking until the answer is valid
while True:
try:
age = int(input("Age: "))
break
except ValueError:
print("Please type a whole number.")
print("Thanks, you are", age)
Age: twenty
Please type a whole number.
Age: 20
Thanks, you are 20
Warning
Never write a bare except: with no exception name. It also catches your own typos, such as a misspelt variable, and silently hides them. Catch the specific exception you expect.
Exceptions you will meet often
ValueError— right type, wrong value, such asint("abc").TypeError— wrong type, such as"a" + 1.KeyError/IndexError— a missing dictionary key or list position.ZeroDivisionError,FileNotFoundError,NameError.
When does the finally block run?
Try this now
- Ask for two numbers and divide them, handling both a non-number and division by zero with clear messages.
- Look up a name in a dictionary with square brackets, catching
KeyErrorto print "Not found".
Create a free account to save your progress, or sign in.