Basic Exception Handling
try:
result = 10 / 0
except ZeroDivisionError as e:
print(f'Error: {e}')
except (TypeError, ValueError) as e:
print(f'Type or value error: {e}')
except Exception as e:
print(f'Unexpected error: {e}')
else:
print('No error occurred')
finally:
print('Always runs')
Custom Exceptions
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
Raising Exceptions
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 must be between 0 and 150, got {age}')
return age
Ready to Level Up Your Coding Skills?
Join Coderz Club and learn to code with challenges, battles, and an AI mentor.
Join Coderz Club Free →