Custom Exceptions
Python mein custom exception banana bahut simple hai — Exception class se inherit karo. Real applications mein custom exceptions bahut common hain, kyunki wo application-specific errors ko clearly represent karte hain aur extra data bhi carry kar sakte hain.
raise keyword se exception explicitly throw karte ho — C++ ke throw jaisa hi concept. Custom exception ka __init__ extra fields le sakta hai (jaise error code), jo except block mein access ho sakte hain.
class InsufficientFundsError(Exception):
def __init__(self, balance, amount):
self.balance = balance
self.amount = amount
super().__init__(f"Balance {balance} se {amount} nahi nikal sakte")
def withdraw(balance, amount):
if amount > balance:
raise InsufficientFundsError(balance, amount)
return balance - amount
try:
withdraw(100, 500)
except InsufficientFundsError as e:
print(f"Error: {e}") # Exception ka __str__ automatically message dikhata hai
print(f"Shortfall: {e.amount - e.balance}") # custom fields access- Exception se inherit karke custom exception types banao
- raise keyword se explicitly throw karo
- Extra fields (jaise balance, amount) exception ke saath carry ho sakte hain
Bade applications mein custom exceptions ki apni hierarchy banti hai — ek base AppException, aur usse derived specific exceptions. Isse ek hi except (AppException) se saare app-specific errors pakad sakte ho.
class AppError(Exception):
"""Base exception for this application"""
pass
class DatabaseError(AppError):
pass
class ValidationError(AppError):
pass
try:
raise DatabaseError("Connection failed")
except AppError as e: # base class catch — DatabaseError bhi pakadta hai
print(f"App error occurred: {e}")assert condition, message ek quick sanity-check hai — agar condition False ho, AssertionError raise hota hai. Usually testing/debugging ke liye use hota hai, production error-handling ke liye nahi (kyunki -O flag se disable ho sakta hai).
def calculate_average(numbers):
assert len(numbers) > 0, "List khaali nahi honi chahiye"
return sum(numbers) / len(numbers)
print(calculate_average([1, 2, 3])) # 2.0
# calculate_average([]) # AssertionError: List khaali nahi honi chahiye