Python Exceptions
Handle errors gracefully — don't let your program crash unexpectedly.
Basic try / except
Python
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
# Program continues running
Access the exception object
Python
try:
int("hello")
except ValueError as e:
print(f"Error: {e}")
# Error: invalid literal for int() with base 10: 'hello'
Catch multiple exceptions
Python
try:
data = open("file.txt").read()
value = int(data)
except FileNotFoundError:
print("File not found")
except ValueError:
print("File contents are not a number")
except (TypeError, OSError) as e: # multiple in one
print(f"System error: {e}")
else and finally
Python
try:
result = 10 / 2
except ZeroDivisionError:
print("Division error")
else:
print(f"Result: {result}") # runs only if NO exception
finally:
print("This always runs") # cleanup code here
Raising exceptions
Python
def set_age(age):
if not isinstance(age, int):
raise TypeError("Age must be an integer")
if age < 0 or age > 150:
raise ValueError(f"Age {age} is out of range (0-150)")
return age
Custom exceptions
Python
class InsufficientFundsError(Exception):
def __init__(self, amount, balance):
self.amount = amount
self.balance = balance
super().__init__(f"Can't withdraw {amount}, balance is {balance}")
def withdraw(amount, balance):
if amount > balance:
raise InsufficientFundsError(amount, balance)
return balance - amount
try:
withdraw(500, 100)
except InsufficientFundsError as e:
print(e) # Can't withdraw 500, balance is 100
Common built-in exceptions
| Exception | When it occurs |
|---|---|
ValueError | Right type, wrong value (int("abc")) |
TypeError | Wrong type ("hello" + 5) |
IndexError | List index out of range |
KeyError | Dict key not found |
AttributeError | Object has no such attribute |
FileNotFoundError | File doesn't exist |
ZeroDivisionError | Divide by zero |
ImportError | Module not found |
StopIteration | Iterator exhausted |
Best practices
Catch specific exceptions (not bare
except:). Don't suppress exceptions with empty except blocks. Use finally for cleanup (closing files, DB connections). Create custom exceptions for your own domain errors.