How to Handle Errors in Python
Learn how to use try/except blocks to handle exceptions and errors in Python.
Error handling in Python uses try/except blocks to gracefully handle exceptions.
Basic Try/Except
Catch and handle errors:
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
Catching Multiple Exceptions
Handle different error types:
try:
value = int("not a number")
except ValueError:
print("Invalid number format")
except TypeError:
print("Type error occurred")
Or catch multiple in one block:
try:
# Some code
pass
except (ValueError, TypeError) as e:
print(f"Error: {e}")
Catching All Exceptions
Use with caution:
try:
# Risky code
result = risky_operation()
except Exception as e:
print(f"An error occurred: {e}")
The else Clause
Runs if no exception occurred:
try:
result = 10 / 2
except ZeroDivisionError:
print("Division error")
else:
print(f"Result: {result}") # Only runs if no error
The finally Clause
Always runs, regardless of exceptions:
try:
file = open("data.txt", "r")
content = file.read()
except FileNotFoundError:
print("File not found")
finally:
file.close() # Always executes
print("Cleanup complete")
Raising Exceptions
Throw your own exceptions:
def validate_age(age):
if age < 0:
raise ValueError("Age cannot be negative")
if age > 150:
raise ValueError("Age seems unrealistic")
return age
try:
validate_age(-5)
except ValueError as e:
print(f"Validation error: {e}")
Custom Exceptions
Create your own exception classes:
class InsufficientFundsError(Exception):
def __init__(self, balance, amount):
self.balance = balance
self.amount = amount
super().__init__(f"Cannot withdraw {amount}. Balance: {balance}")
def withdraw(balance, amount):
if amount > balance:
raise InsufficientFundsError(balance, amount)
return balance - amount
try:
withdraw(100, 150)
except InsufficientFundsError as e:
print(e) # Cannot withdraw 150. Balance: 100
Common Exceptions
| Exception | When it occurs |
|---|---|
ValueError | Invalid value for operation |
TypeError | Wrong type for operation |
KeyError | Dictionary key not found |
IndexError | List index out of range |
FileNotFoundError | File doesn’t exist |
ZeroDivisionError | Division by zero |
Summary
- Use
try/exceptto catch and handle errors - Be specific about which exceptions to catch
- Use
elsefor code that runs only on success - Use
finallyfor cleanup code - Use
raiseto throw exceptions