Python Try Except
try and except are blocks that catch an error in running code.
A bad value with no handler
This code has no try block. The bad value raises ValueError and stops the program.
number = int("abc")
print(number)Try risky code
The risky line sits inside the try block.
try:
number = int("42")
print(number)
except ValueError:
print("Not a number")Catch a bad value
Bad text makes int() fail. The except block answers instead.
try:
number = int("abc")
print(number)
except ValueError:
print("Not a number")The program survives
A caught error does not end the program.
try:
print(10 / 0)
except ZeroDivisionError:
print("Cannot divide by zero")
print("Program still running")A named except is picky
This block waits for ValueError only. A division error slips past it.
try:
print(10 / 0)
except ValueError:
print("Not a number")Example
while True:
text = input("Enter your age: ")
try:
age = int(text)
break
except ValueError:
print("Please type a whole number.")
print("Your age is", age)Key points
- Use try to wrap the lines that might fail
- Use except to catch an error and handle it
- Catching one named error beats catching every error
- A caught error does not stop the program
In this example, the loop asks for your age again and again. With this input: abc, then 25. The first try turns abc into a number and fails. The except block prints a friendly message. The loop then asks again. The second try turns 25 into a number and works. break leaves the loop at that point. The program then prints your age as 25.
Note
A bare except hides other bugs.
Name the error you expect whenever you can.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Python Playground
Exercise
Your code converts typed text into a number. Which except block is the better choice?