
🐍 Lesson 13: Custom Exceptions
1. Custom Exception ဆိုတာဘာလဲ?
မြန်မာ → Python မှာ built-in exceptions (ValueError, TypeError, ZeroDivisionError) အပြင်, ကိုယ်ပိုင် error type ကို ဖန်တီးနိုင်တယ်။
English → Besides built-in exceptions, Python allows you to define your own exception classes, called custom exceptions, to represent specific error conditions.
2. Why Use Custom Exceptions?
- Clearer error messages
- Domain-specific error handling
- Easier debugging and maintenance
- Makes code more readable
3. အကျဉ်းချုပ်
✅ Custom exceptions = user-defined error types
✅ Inherit from Exception
✅ Useful for domain-specific error handling
✅ Can add attributes for more context
python
# ===== 1. Basic Custom Exception =====
class MyError(Exception):
"""Custom exception class"""
pass
try:
raise MyError("Something went wrong")
except MyError as e:
print(f"Caught custom error: {e}")
# ===== 2. Adding Attributes =====
print(f"\n===== Exception with Attributes =====")
class ValidationError(Exception):
def __init__(self, field, message):
self.field = field
self.message = message
super().__init__(f"{field}: {message}")
try:
raise ValidationError("username", "must not be empty")
except ValidationError as e:
print(f"Error in {e.field} - {e.message}")
# ===== 3. Hierarchy of Custom Exceptions =====
print(f"\n===== Exception Hierarchy =====")
class AppError(Exception):
"""Base class for app errors"""
pass
class DatabaseError(AppError):
pass
class AuthenticationError(AppError):
pass
try:
raise AuthenticationError("Invalid password")
except AppError as e:
print(f"App error: {e}")
# ===== 4. Real-World Example: Bank Account =====
print(f"\n===== Bank Account Example =====")
class InsufficientFundsError(Exception):
pass
class BankAccount:
def __init__(self, balance):
self.balance = balance
def withdraw(self, amount):
if amount > self.balance:
raise InsufficientFundsError("Not enough balance")
self.balance -= amount
return self.balance
try:
account = BankAccount(100)
account.withdraw(200)
except InsufficientFundsError as e:
print(f"Withdrawal failed: {e}")You should see
Caught custom error: Something went wrong ===== Exception with Attributes ===== Error in username - must not be empty ===== Exception Hierarchy ===== App error: Invalid password ===== Bank Account Example ===== Withdrawal failed: Not enough balance