ရိုးရိုးလေး ရှင်းပြမယ်
ရိုးရိုးလေး ရှင်းရရင်
ဆေးရုံ အရေးပေါ်ဌာနကို စဉ်းစားကြည့်ပါ။ လူနာတစ်ယောက် ရောက်လာရင် "နေမကောင်းဘူး" လို့ပဲ ပြောရင် ဆရာဝန်တွေ ဘယ်ဌာနကို ပို့ရမလဲ မသိပါဘူး။ "ခြေထောက် ကျိုးတယ်" လို့ တိတိကျကျ ပြောမှ အရိုးဌာနကို တန်းပို့လို့ ရပါတယ်။ Exception တွေကလည်း ဒီလိုပါပဲ — error ရဲ့ အမျိုးအစား (class) က ဘယ်သူ ကိုင်တွယ်ရမလဲ ဆုံးဖြတ်ပါတယ်။
ဌာနတွေကလည်း အဆင့်ဆင့် ဖွဲ့ထားပါတယ် — "ခွဲစိတ်ဌာန" အောက်မှာ "အရိုး" နဲ့ "နှလုံး" ရှိသလို Python မှာ LookupError အောက်မှာ KeyError နဲ့ IndexError ရှိပါတယ်။ ကိုယ့် application အတွက်လည်း InsufficientFundsError လို နာမည်တိကျတဲ့ exception class တွေ ကိုယ်တိုင် ဆောက်ပြီး raise နဲ့ ထုတ်ပေးလို့ ရပါတယ်။
Problem → Why → Solution
ပြဿနာ: ယေဘုယျ Exception နဲ့ message စာသားကို ခန့်မှန်းနေရတာ
withdraw() က ငွေမလောက်ရင် ယေဘုယျ Exception ကို raise လုပ်ပါတယ်။ Caller ဘက်က ဒီ error ကိုပဲ ဖမ်းချင်ပေမယ့် except Exception: ကလွဲပြီး ရွေးစရာ မရှိလို့ typo နဲ့ bug တွေပါ ဖမ်းမိပါတယ်။ ပြီးတော့ message ထဲမှာ "balance" ဆိုတဲ့ စကားလုံး ပါမပါ စစ်ပြီး ခန့်မှန်းနေရပါတယ်။ တစ်နေ့ message ကို "Insufficient funds" လို့ ပြောင်းလိုက်တာနဲ့ caller logic က အသံတိတ် ပျက်သွားပါတယ်။
def withdraw(balance, amount):
if amount > balance:
raise Exception("Not enough balance") # no specific type
return balance - amount
try:
withdraw(100, 500)
except Exception as e: # catches bugs too
if "balance" in str(e): # guessing from the text
print("ask the user for a smaller amount")ဘာကြောင့် ဒီ design က မကောင်းတာလဲ
except clause တွေက message စာသားကို မကြည့်ဘဲ exception ရဲ့ class နဲ့ပဲ ရွေးပါတယ်။ Error အမျိုးအစားတိုင်းမှာ ကိုယ်ပိုင် class မရှိရင် caller က တိကျစွာ ရွေးဖမ်းလို့ မရပါဘူး။ class InsufficientFundsError(Exception) တစ်ခု ဆောက်ပြီး raise လုပ်ရင် caller က except InsufficientFundsError: လို့ ရေးနိုင်ပြီး message ပြောင်းလည်း မပျက်တော့ပါဘူး၊ shortfall လို ဒေတာကိုလည်း attribute အဖြစ် သယ်ပေးနိုင်ပါတယ်။
Core concept: exception တွေက class hierarchy တစ်ခုပါ
Python ရဲ့ exception တိုင်းက class တစ်ခုဖြစ်ပြီး BaseException ဆီကနေ ဆက်ခံထားပါတယ်။ except SomeError: က SomeError ကိုရော သူ့ subclass အားလုံးကိုပါ ဖမ်းပါတယ် — ဒါက ပြီးခဲ့တဲ့ lesson တွေက inheritance နဲ့ isinstance() စည်းမျဉ်းအတိုင်းပါပဲ။ ဒါကြောင့် except LookupError: က KeyError ရော IndexError ပါ ဖမ်းပါတယ်။
Part of Python's built-in exception hierarchy
---------------------------------------------
BaseException
+-- SystemExit (sys.exit())
+-- KeyboardInterrupt (Ctrl+C)
+-- Exception <- your own exceptions inherit from here
+-- ArithmeticError
| +-- ZeroDivisionError
+-- LookupError
| +-- IndexError
| +-- KeyError
+-- OSError
| +-- FileNotFoundError
+-- TypeError
+-- ValueErrorSystemExit နဲ့ KeyboardInterrupt က Exception အောက်မှာ မရှိဘဲ BaseException ရဲ့ တိုက်ရိုက် child တွေပါ။ ဒါကြောင့် except Exception: က program ပိတ်ဖို့ တောင်းဆိုမှုတွေကို မဖမ်းပါဘူး။ ကိုယ်ပိုင် exception တွေကို BaseException ကနေ မဆက်ခံဘဲ Exception (ဒါမှမဟုတ် သူ့ subclass) ကနေ အမြဲ ဆက်ခံပါ။
Exception object ကလည်း ရိုးရိုး instance တစ်ခုပါပဲ: e.args ထဲမှာ constructor ကို ပို့ခဲ့တဲ့ argument တွေ၊ str(e) မှာ message၊ e.__traceback__ မှာ ဘယ်နေရာက raise ဖြစ်ခဲ့လဲ ဆိုတဲ့ မှတ်တမ်း ရှိပါတယ်။ raise ဖြစ်တာနဲ့ Python က ကိုက်တဲ့ except တွေ့တဲ့အထိ call stack ကို တစ်ဆင့်ချင်း ပြန်တက်သွားလို့ code ရဲ့ အနက်ဆုံး function တစ်ခုက အဆင့် အများကြီး အပေါ်မှာရှိတဲ့ caller ကို ပြဿနာ သတင်းပို့နိုင်ပါတယ်၊ ကြားက function တိုင်းက return code ကို စစ်ပေးနေစရာ မလိုပါဘူး။
raise statement က exception ကို ထုတ်ပါတယ်: raise ValueError("age must be positive")။ Built-in type တစ်ခုက အဓိပ္ပာယ် ကိုက်ရင် အဲဒါကို သုံးပါ — type မှားတာဆိုရင် TypeError၊ type မှန်ပေမယ့် value မမှန်ရင် ValueError။ Application ရဲ့ business rule တွေ (ငွေမလောက်တာ၊ order ပိတ်ပြီးသားဖြစ်တာ) အတွက်တော့ custom exception class ဆောက်ပါ။ Custom exception က ရိုးရိုး class တစ်ခုပါပဲ: class AppError(Exception): လို့ ရေးပြီး ကိုယ်ပိုင် __init__ နဲ့ attribute တွေ ထည့်လို့ ရပါတယ်၊ super().__init__(message) ကိုတော့ ခေါ်ပါ၊ ဒါမှ str(e) က message ကို ပြမှာပါ။
Application တစ်ခုလုံးအတွက် AppError လို base class တစ်ခု ထားပြီး ValidationError, InsufficientFundsError စတာတွေကို အောက်မှာ ဆောက်ရင် caller က အမျိုးအစား တစ်ခုချင်း ဒါမှမဟုတ် except AppError: နဲ့ app error အားလုံးကို တစ်ပြိုင်နက် ရွေးဖမ်းနိုင်ပါတယ်။ Exception တွေကို ပုံမှန် branching (if/else နဲ့ ရေးလို့ရတဲ့ အခြေအနေ) အတွက် မသုံးပါနဲ့၊ input validation boundary၊ I/O နဲ့ တကယ် ထူးခြားတဲ့ အခြေအနေတွေအတွက်ပဲ သုံးပါ။
- raise SomeError(...) က object ဖန်တီး
- Call stack တစ်ဆင့်ချင်း အပေါ်တက်
- isinstance ကိုက်တဲ့ except က ဖမ်း
- ဘယ်သူမှ မဖမ်းရင် traceback + ရပ်
except Parent: က Parent ရဲ့ subclass exception အားလုံးကို ဖမ်းပါတယ်၊ ဒါကြောင့် hierarchy ဒီဇိုင်းက အရေးကြီးပါတယ်။
အထွေထွေ ပုံစံ
class AppError(Exception):
"""Base for all errors this app raises."""
class SpecificError(AppError):
def __init__(self, detail):
super().__init__(f"readable message about {detail}")
self.detail = detail
raise SpecificError(value) # throw it
raise SpecificError(value) from original # keep the cause
raise # inside except: re-raise as isApp-wide base class တစ်ခု ထားပြီး အမျိုးအစား တစ်ခုစီကို subclass အဖြစ် ဆောက်ပါ။ super().__init__() က message ကို သိမ်းပြီး ကိုယ်ပိုင် attribute တွေက caller အတွက် ဒေတာ သယ်ပါတယ်။ raise ပုံစံ သုံးမျိုးကို အောက်က deeper section မှာ အသေးစိတ် ကြည့်ပါမယ်။
Example: ဘဏ်ငွေထုတ်ခြင်းအတွက် custom exception များ
AppError base class အောက်မှာ ValidationError နဲ့ InsufficientFundsError ကို ဆောက်ပြီး withdraw() က အခြေအနေအလိုက် raise လုပ်ပါတယ်။ Caller က ValidationError ကို သီးသန့် ကိုင်တွယ်ပြီး ကျန်တဲ့ app error တွေကို except AppError နဲ့ ဖမ်းပါတယ်။ နောက်ဆုံး line က built-in ZeroDivisionError ရဲ့ ဆက်ခံမှု ကွင်းဆက်ကို ပြပါတယ်။
class AppError(Exception):
"""Base class for every error this app raises on purpose."""
class ValidationError(AppError):
def __init__(self, field, message):
super().__init__(f"{field}: {message}") # sets str(e)
self.field = field
class InsufficientFundsError(AppError):
def __init__(self, balance, amount):
super().__init__(f"need {amount}, have {balance}")
self.shortfall = amount - balance
def withdraw(balance, amount):
if amount <= 0:
raise ValidationError("amount", "must be positive")
if amount > balance:
raise InsufficientFundsError(balance, amount)
return balance - amount
for amount in [30, -5, 500]:
try:
print("new balance:", withdraw(100, amount))
except ValidationError as e:
print(f"bad field {e.field!r} -> {e}")
except AppError as e: # any other app error
print(f"{type(e).__name__}: {e}")
print(issubclass(InsufficientFundsError, AppError))
print([cls.__name__ for cls in ZeroDivisionError.__mro__])Code ကို တစ်ပိုင်းချင်း ရှင်းပြမယ်
- Line 1
class AppError(Exception):Application ရဲ့ error အားလုံးအတွက် base class ပါ။ Body မှာ docstring ပဲ ရှိပေမယ့် class တစ်ခု ဖြစ်ဖို့ လုံလောက်ပါတယ်။
- Line 7
super().__init__(f"{field}: {message}") # sets str(e)Exception.__init__ ကို message ပို့လိုက်လို့ str(e) က "amount: must be positive" ဖြစ်ပါတယ်။ ဒီ line မပါရင် str(e) က ဖတ်ရလွယ်တဲ့ message အစား constructor argument အကြမ်းတွေ ('amount', 'must be positive') ကိုပဲ ပြပါတယ်။
- Line 14
self.shortfall = amount - balanceException ကလည်း object ပဲမို့ caller သုံးဖို့ ဒေတာကို attribute အဖြစ် သယ်လို့ ရပါတယ်။ Message စာသားကို parse လုပ်စရာ မလိုတော့ပါဘူး။
- Line 21
raise InsufficientFundsError(balance, amount)raise က exception object ကို ဖန်တီးပြီး ထုတ်လိုက်ပါတယ်။ withdraw() ရဲ့ ကျန်တဲ့ code မ run တော့ဘဲ caller ရဲ့ try ဆီ ချက်ချင်း ခုန်သွားပါတယ်။
- Line 30
except AppError as e: # any other app errorInsufficientFundsError က AppError ရဲ့ subclass ဖြစ်လို့ ဒီ clause က ဖမ်းပါတယ်။ ValidationError ကတော့ အပေါ်က clause က အရင် ဖမ်းပြီးသားပါ။
- Line 34
print([cls.__name__ for cls in ZeroDivisionError.__mro__])Built-in exception တွေလည်း class hierarchy ထဲမှာ ရှိကြောင်း ပြပါတယ်: ZeroDivisionError → ArithmeticError → Exception → BaseException → object။
new balance: 70
bad field 'amount' -> amount: must be positive
InsufficientFundsError: need 500, have 100
True
['ZeroDivisionError', 'ArithmeticError', 'Exception', 'BaseException', 'object']
raise ... from ... နဲ့ exception chaining
Low-level error (KeyError, ValueError) ကို ဖမ်းပြီး caller နားလည်တဲ့ domain error (ConfigError) အဖြစ် ပြောင်းချင်တဲ့အခါ raise NewError(...) from original လို့ ရေးပါ။ မူလ exception က e.__cause__ ထဲမှာ သိမ်းထားပြီး traceback မှာ "The above exception was the direct cause of the following exception" ဆိုပြီး နှစ်ခုလုံး ပေါ်ပါတယ်။ ဒါကြောင့် context ထပ်ထည့်ရင်း debug အတွက် အချက်အလက် ဘာမှ မပျောက်ပါဘူး။
class ConfigError(Exception):
pass
def read_port(settings):
try:
return int(settings["port"])
except (KeyError, ValueError) as e:
raise ConfigError("port must be a whole number") from e
try:
read_port({"port": "eighty"})
except ConfigError as e:
print("ConfigError:", e)
print("caused by:", repr(e.__cause__))Bare raise နဲ့ ပြန် raise လုပ်ခြင်း
except block ထဲမှာ log ရေးတာလို အလုပ်တစ်ခု လုပ်ပြီး error ကို ဆက်တက်ခွင့်ပေးချင်ရင် raise ကို argument မပါဘဲ ရေးပါ။ အဲဒါက ဖမ်းထားတဲ့ exception တစ်ခုတည်းကို မူလ traceback နဲ့အတူ ပြန်ထုတ်ပါတယ်။ raise e လို့ ရေးလည်း အလုပ်လုပ်ပေမယ့် traceback ထဲမှာ ဒီ line ကို ထပ်ထည့်လို့ bare raise က ပိုရှင်းပါတယ်။
def save(record):
raise PermissionError("database is read-only")
def save_with_log(record):
try:
save(record)
except PermissionError:
print("log: save failed for", record)
raise # same exception, original traceback
try:
save_with_log({"id": 7})
except PermissionError as e:
print("caller saw:", e)လက်တွေ့ project တွေမှာ
Real project တွေမှာ ဘယ်လို သုံးလဲ
Library ကောင်းတွေတိုင်းမှာ ကိုယ်ပိုင် exception hierarchy ရှိပါတယ်။ requests library မှာ RequestException အောက်မှာ ConnectionError, Timeout, HTTPError စတာတွေ ရှိလို့ user က timeout ကိုပဲ retry လုပ်တာ ဒါမှမဟုတ် except RequestException: နဲ့ network ပြဿနာ အားလုံးကို တစ်ပြိုင်နက် ကိုင်တွယ်တာ ရွေးလို့ ရပါတယ်။ Django မှာလည်း ObjectDoesNotExist, ValidationError, PermissionDenied လို exception တွေကို framework က HTTP 404, 400, 403 response တွေအဖြစ် အလိုအလျောက် ပြောင်းပေးပါတယ်။
ကိုယ်ပိုင် service တွေမှာလည်း PaymentError(AppError) လို exception တွေက code ("card_declined") နဲ့ user ကို ပြလို့ ဘေးကင်းတဲ့ message ကို attribute အဖြစ် သယ်ပါတယ်။ API layer က except AppError as e: နဲ့ ဖမ်းပြီး e.code ကို JSON response ထဲ ထည့်ပေးပါတယ်။ Database driver ရဲ့ error ကို raise PaymentError(...) from e နဲ့ ပြောင်းထားလို့ user က internal detail ကို မမြင်ရပေမယ့် developer က log ထဲမှာ မူလ cause ကို အပြည့် မြင်ရပါတယ်။
အမှားများ
အဖြစ်များတဲ့ အမှားတွေ
1. BaseException ကနေ ဆက်ခံတာ
class MyError(BaseException): လို့ ရေးရင် except Exception: နဲ့ ဖမ်းလို့ မရတော့ပါဘူး၊ top-level error handler တွေကို ကျော်သွားပြီး program တစ်ခုလုံး ရပ်သွားနိုင်ပါတယ်။ BaseException က SystemExit, KeyboardInterrupt လို interpreter အဆင့် signal တွေအတွက်ပါ၊ ကိုယ်ပိုင် exception တွေကို Exception ကနေ ဆက်ခံပါ။
2. Custom __init__ မှာ super().__init__() မေ့တာ
__init__ ထဲမှာ self.field = field ပဲ ရေးပြီး super().__init__(message) မခေါ်ရင် str(e) က ကိုယ်ရည်ရွယ်ထားတဲ့ message မဟုတ်ဘဲ constructor ကို ပို့ခဲ့တဲ့ argument အကြမ်းတွေကိုပဲ ပြပါတယ် — ValidationError("amount", "must be positive") ဆိုရင် ('amount', 'must be positive') လို tuple ပုံစံ ပေါ်ပါတယ်။ Argument တွေကို keyword နဲ့ ပို့ရင်တော့ str(e) က အလွတ် string တောင် ဖြစ်သွားပြီး log ထဲမှာ ဘာမှားလဲ မသိရပါဘူး။ message ကို parent ဆီ အမြဲ ပို့ပါ။
3. raise ... from မပါဘဲ ပြောင်း raise လုပ်ပြီး cause ပျောက်တာ
except KeyError: raise ConfigError("bad config") from None လို့ ရေးရင် မူလ KeyError ကို traceback ကနေ ဖျောက်လိုက်ပါတယ်။ from None ကို user ကို ပြတဲ့ CLI message လို တကယ်လိုမှပဲ သုံးပြီး ပုံမှန်အားဖြင့် from e နဲ့ cause ကို ချိတ်ထားပါ။
Mini challenge
Mini challenge: config loader အတွက် exception hierarchy
Config dictionary တစ်ခုကို စစ်ပေးတဲ့ load_config() ရေးပါ။ ပြဿနာ အမျိုးအစား တစ်ခုစီအတွက် ConfigError အောက်မှာ ကိုယ်ပိုင် exception class ရှိရပါမယ်။
- ConfigError(Exception) base class အောက်မှာ MissingKeyError နဲ့ InvalidValueError ဆောက်ရမယ်၊ နှစ်ခုလုံး key attribute ရှိရမယ်
- "host" ဒါမှမဟုတ် "port" မပါရင် MissingKeyError raise လုပ်ရမယ်
- port ကို int() ပြောင်းလို့ မရရင် InvalidValueError ကို from e နဲ့ raise လုပ်ရမယ်
- port က 1-65535 ပြင်ပ ဖြစ်ရင်လည်း InvalidValueError raise လုပ်ရမယ်
class ConfigError(Exception):
"""Base class for configuration problems."""
class MissingKeyError(ConfigError):
def __init__(self, key):
# TODO: pass a readable message to the parent and keep self.key
pass
# TODO: InvalidValueError(ConfigError) taking key and value
def load_config(raw):
# TODO: raise MissingKeyError for a missing "host" or "port"
# TODO: convert the port with int(); on ValueError raise ... from e
# TODO: reject ports outside 1..65535
# TODO: return {"host": ..., "port": ...}
pass
# TODO: try four samples (valid, missing port, "http", "70000") and print
# "ok:", "missing:" or "invalid:" for each, including the cause typeရလဒ်: Output က ဒီလို ထွက်ရပါမယ်: ok: {'host': 'localhost', 'port': 8080} missing: port invalid: 'port' has invalid value 'http' (cause: ValueError) invalid: 'port' has invalid value 70000 (cause: none)
အရိပ်အမြွက် ကြည့်ရန်
e.__cause__ က from နဲ့ ချိတ်ထားရင် မူလ exception ဖြစ်ပြီး မချိတ်ရင် None ပါ။ MissingKeyError ကို ConfigError ထက် အရင် except လုပ်ပါ၊ subclass ဖြစ်လို့ပါ။
အဖြေ ကြည့်ရန်
class ConfigError(Exception):
"""Base class for configuration problems."""
class MissingKeyError(ConfigError):
def __init__(self, key):
super().__init__(f"missing required key {key!r}")
self.key = key
class InvalidValueError(ConfigError):
def __init__(self, key, value):
super().__init__(f"{key!r} has invalid value {value!r}")
self.key = key
def load_config(raw):
for key in ("host", "port"):
if key not in raw:
raise MissingKeyError(key)
try:
port = int(raw["port"])
except ValueError as e:
raise InvalidValueError("port", raw["port"]) from e
if not 1 <= port <= 65535:
raise InvalidValueError("port", port)
return {"host": raw["host"], "port": port}
samples = [
{"host": "localhost", "port": "8080"},
{"host": "localhost"},
{"host": "localhost", "port": "http"},
{"host": "localhost", "port": "70000"},
]
for raw in samples:
try:
print("ok:", load_config(raw))
except MissingKeyError as e:
print("missing:", e.key)
except ConfigError as e:
cause = type(e.__cause__).__name__ if e.__cause__ else "none"
print(f"invalid: {e} (cause: {cause})")Quick Quiz 1 / 3
Quick Quiz 2 / 3
Quick Quiz 3 / 3
မှတ်ထားရမယ့် အချက်များ
- Exception တိုင်းက BaseException အောက်က class တစ်ခုဖြစ်ပြီး except Parent: က subclass အားလုံးကို ဖမ်းပါတယ်။
- Built-in type ကိုက်ရင် raise ValueError/TypeError သုံးပြီး business rule တွေအတွက် custom exception ဆောက်ပါ။
- Custom exception တွေကို Exception ကနေ app-wide base class တစ်ခုအောက်မှာ ဆောက်ပြီး super().__init__(message) ခေါ်ပါ။
- raise ... from e က cause ကို ချိတ်ပြီး bare raise က ဖမ်းထားတဲ့ exception ကို traceback မပျက်ဘဲ ပြန်ထုတ်ပါတယ်။
Python Documentation — Errors and Exceptions — Python Software Foundation