How to Use Try and Except in Python
What you’ll build or solve
You’ll handle errors without crashing your program by using try and except.
When this approach works best
try and except work well when you:
Learn Python on Mimo
- Parse user input that might be invalid, like converting text to an integer.
- Work with files or network calls that might fail, like missing files or timeouts.
- Access dictionary keys or list indexes that might not exist, and you want a fallback.
Avoid try/except for normal control flow when you can prevent the error with a simple check. For example, check key in d or use get() instead of relying on KeyError in code that runs all the time.
Prerequisites
- Python installed
- You know what an exception is at a high level
Step-by-step instructions
1) Wrap risky code in try, then handle errors in except
Put code that might fail inside try. Catch the specific exception type in except.
text="12a"
try:
value=int(text)
print(value)
exceptValueError:
print("Please enter a whole number.")
What to look for:
Catching ValueError keeps other bugs visible. If you catch too broadly, you might hide real problems.
2) Catch multiple exception types cleanly
If different errors can happen, catch them separately, or group them when the handling is the same.
data= {"count":"10"}
try:
count=int(data["count"])
exceptKeyError:
count=0
exceptValueError:
count=0
print(count)
Option A: Group exceptions with the same handling
data= {"count":"10"}
try:
count=int(data["count"])
except (KeyError,ValueError):
count=0
print(count)
What to look for:
Put more specific except blocks first. Python matches from top to bottom.
3) Use else for code that should run only when no error happens
else runs if the try block succeeds. This keeps the success path separate from error handling.
text="42"
try:
value=int(text)
exceptValueError:
print("Invalid number.")
else:
print("Parsed:",value)
What to look for:
else prevents you from accidentally running “success” code when the try failed and you set a fallback value.
Examples you can copy
Example 1: Convert input to an integer with a fallback
text="7"
try:
n=int(text)
exceptValueError:
n=0
print(n)
Example 2: Read a file and handle a missing path
path="config.json"
try:
withopen(path,"r",encoding="utf-8")asf:
data=f.read()
exceptFileNotFoundError:
data="{}"
print(data)
Example 3: Safely access a dictionary key
user= {"name":"Naomi"}
try:
email=user["email"]
exceptKeyError:
email=""
print(email)
Example 4: Parse a float, then compute
text="3.14"
try:
x=float(text)
exceptValueError:
print("Not a number.")
else:
print(x*2)
Example 5: Retry a task a few times on failure
attempts=0
max_attempts=3
success=False
whileattempts<max_attempts:
attempts+=1
try:
value=int(input("Enter a number: ").strip())
exceptValueError:
print("Try again.")
continue
success=True
break
print("Success:",success)
Example 6: Use finally for cleanup when with isn’t available
This is less common than with open(...). Use finally when you need cleanup across multiple exit paths.
f=None
try:
f=open("notes.txt","r",encoding="utf-8")
content=f.read()
print(content)
exceptFileNotFoundError:
print("File not found.")
finally:
iffisnotNone:
f.close()
Common mistakes and how to fix them
Mistake 1: Catching Exception and hiding bugs
What you might do
try:
value=int("12a")
exceptException:
value=0
Why it breaks
This catches too much, including errors you did not expect. Debugging gets harder.
Fix
Catch the specific exception:
try:
value=int("12a")
exceptValueError:
value=0
Mistake 2: Using try/except where a simple check is clearer
What you might do
user= {"name":"Naomi"}
try:
email=user["email"]
exceptKeyError:
email=""
Why it breaks
This works, but it is noisier than necessary for a common, expected case.
Fix
Use get() for a simple default:
user= {"name":"Naomi"}
email=user.get("email","")
Troubleshooting
If your except never runs, you might be catching the wrong exception type. Run without try once to see the exception name.
If your code still crashes, the error is happening outside the try block. Move only the risky lines inside try.
If everything gets swallowed, you are catching too broadly. Replace except Exception with a specific exception type.
If a loop keeps retrying indefinitely, track attempts and stop after a limit.
If cleanup does not happen, use with for files, or finally when cleanup must happen across different exit paths.
Quick recap
- Put risky code inside
try. - Catch specific exceptions in
except. - Group exceptions when the handling is the same.
- Use
elsefor code that should run only when no exception happened. - Use
finallyfor cleanup that must run even on errors.
Join 35M+ people learning for free on Mimo
4.8 out of 5 across 1M+ reviews
Check us out on Apple AppStore, Google Play Store, and Trustpilot