How to Handle Exceptions in Python
Ad
Exception Handling Basics
Exceptions are errors that occur while a program runs. Python's try/except lets you catch them gracefully instead of crashing.
The try/except Block
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
Catching Specific Exceptions
try:
value = int(user_input)
except ValueError:
print("Not a valid number")
except KeyError:
print("Missing key")
else and finally
try:
f = open("data.txt")
except FileNotFoundError:
print("No file")
else:
print("File opened OK") # runs if no exception
finally:
print("Always runs") # cleanup, always executes
Raising Your Own
def withdraw(amount):
if amount < 0:
raise ValueError("Amount must be positive")
Best Practices
- Catch specific exceptions, not bare
except:. - Use
finallyor context managers (with) for cleanup. - Don't silence errors you can't handle.
FAQs
What's wrong with except: pass?
It hides all errors including bugs. Always catch specific types. More in our Python guides.
try/except vs if checks?
Python favors "ask forgiveness" (try/except) for exceptional cases, and if for expected control flow.
