// python · beginner
Python try and except: Handle Errors Without Crashing
Learn how to catch errors in Python with try and except, handle specific exceptions, use else and finally, and keep asking for input until it's valid.
So far, when something goes wrong in your program, Python stops and prints an error. That’s helpful while you’re writing code, but it’s a terrible experience for someone using your program. If they type “ten” instead of “10”, the whole thing shouldn’t crash. Python’s try and except let you catch errors and decide what happens instead.
If you’re not yet comfortable reading error messages, start with How to Read Error Messages.
Errors are called exceptions
When Python hits a problem while running, it raises an exception. Each kind has a name, such as ValueError or ZeroDivisionError. Without any handling, an exception stops the program:
age = int(input("How old are you? "))
print(f"Next year you'll be {age + 1}")
Type fifteen and you’ll see:
ValueError: invalid literal for int() with base 10: 'fifteen'
Catching an exception
Wrap the risky code in a try block, and put what should happen instead in an except block:
try:
age = int(input("How old are you? "))
print(f"Next year you'll be {age + 1}")
except ValueError:
print("Please type your age as a number, like 15.")
Python runs the try block. If a ValueError happens anywhere inside it, Python jumps straight to the except block and then carries on with the rest of the program. If nothing goes wrong, the except block is skipped.
Catch specific exceptions
Always name the exception you expect. A bare except: catches everything, including typos in your own code, which hides real bugs:
# Avoid this: it hides every possible problem
try:
total = prise * 2 # a typo! prise doesn't exist
except:
print("Something went wrong")
That code prints “Something went wrong” and you’d never know you’d misspelled price. With except ValueError: instead, the NameError would show up and you’d fix it in seconds.
Handling more than one kind
Different problems can deserve different messages:
try:
a = int(input("First number: "))
b = int(input("Second number: "))
print(f"{a} ÷ {b} = {a / b}")
except ValueError:
print("Those need to be whole numbers.")
except ZeroDivisionError:
print("You can't divide by zero.")
If you want the same response for several exceptions, group them in brackets:
except (ValueError, ZeroDivisionError):
print("Please enter two numbers, and don't use 0 as the second one.")
Seeing the error message
You can capture the exception itself with as, which is useful for showing or logging details:
try:
number = int("12a")
except ValueError as error:
print(f"Couldn't convert: {error}")
# Couldn't convert: invalid literal for int() with base 10: '12a'
else and finally
A try statement can have two more optional parts:
elseruns only if no exception happened;finallyruns no matter what, which is good for tidying up.
try:
value = int(input("Enter a number: "))
except ValueError:
print("That wasn't a number.")
else:
print(f"Its square is {value ** 2}")
finally:
print("Thanks for using the squarer!")
Putting the “success” code in else keeps the try block small, so you only catch errors from the line you actually expect to fail.
Keep asking until the input is valid
This is the pattern you’ll use most. Combine while True with try and break:
while True:
try:
age = int(input("How old are you? "))
break # only reached if int() worked
except ValueError:
print("Please enter a whole number.")
print(f"Thanks! You are {age}.")
Because break comes after the conversion, the loop only ends when the user types something valid. You can add extra checks too:
while True:
try:
rating = int(input("Rate us from 1 to 5: "))
if 1 <= rating <= 5:
break
print("The rating must be between 1 and 5.")
except ValueError:
print("Please enter a number.")
Turning it into a reusable function
Once you’ve written that loop twice, put it in a function:
def ask_int(prompt, low=None, high=None):
while True:
try:
value = int(input(prompt))
except ValueError:
print("Please enter a whole number.")
continue
if low is not None and value < low:
print(f"The number must be at least {low}.")
elif high is not None and value > high:
print(f"The number must be at most {high}.")
else:
return value
age = ask_int("Age: ", 0, 120)
rating = ask_int("Rating (1-5): ", 1, 5)
Now every number you ask for is validated in one line.
Raising your own exceptions
Your own functions can raise exceptions when they’re given something that makes no sense, using raise:
def set_volume(level):
if not 0 <= level <= 10:
raise ValueError("Volume must be between 0 and 10")
print(f"Volume set to {level}")
set_volume(7) # Volume set to 7
set_volume(15) # ValueError: Volume must be between 0 and 10
This is better than quietly doing the wrong thing, because the problem is reported where it starts.
When not to use try
try is for things you can’t control: what a user types, whether a file exists, whether the internet is working. It’s not a way to hide bugs in your own logic. If you can simply check something first, such as if b != 0:, that’s often clearer.
Key points
tryruns risky code;except SomeErrorhandles that specific problem.- Name the exceptions you expect; avoid a bare
except:. elseruns when nothing failed;finallyalways runs.while True+try+breakkeeps asking until input is valid.raiselets your own functions report bad values.
Next, put this into practice with something that often fails: Reading and Writing Files in Python.