Python tana sarrafa kaiɗe tare da try/except sakaye, sannan zaɓen else da finally. Python na ɗambara ƙa'idoɗin EAFP — "Easier to Ask Forgiveness than Permission" — ƙoƙarin aiki da sarrafi kaiɗe a madadin bincika sharrai da farko.
Python tana sarrafa kaiɗe tare da try/except sakaye, sannan zaɓen else da finally. Python na ɗambara ƙa'idoɗin EAFP — "Easier to Ask Forgiveness than Permission" — ƙoƙarin aiki da sarrafi kaiɗe a madadin bincika sharrai da farko.
try:
result = risky_operation()
except ValueError as e: # catch a SPECIFIC exception type
print(f"bad value: {e}")
except (KeyError, IndexError): # catch multiple types
print("lookup failed")
except Exception as e: # catch-all (use sparingly, last)
print(f"unexpected: {e}")
else:
print("ran only if NO exception occurred")
finally:
cleanup() # ALWAYS runs (success or failure)
except SpecificError — kama nau'oji takaici (zaɓi kaɗai a kan sauya gida).else — gudu kawai idan babu kaiɗe da aka tashi.finally — koyaushe gudu (tsarkakewa, sakin albarkatau), har ma da kaiɗe ta yaɗa.# LBYL ("Look Before You Leap") — check first
if key in my_dict:
value = my_dict[key]
# EAFP ("Easier to Ask Forgiveness") — try it, handle failure — more Pythonic
try:
value = my_dict[key]
except KeyError:
value = default
Python ta son EAFP — ƙoƙari aiki da kama kaiɗe — wanda ya guje hawa-kayan motsa jiki da kuma sauƴi fi jiya bincika.
if amount < 0:
raise ValueError("amount must be positive") # raise a built-in
class InsufficientFundsError(Exception): # custom exception type
pass
raise InsufficientFundsError("balance too low")
# ❌ bare except hides bugs (catches EVERYTHING, even typos/KeyboardInterrupt)
try: ...
except: pass
# ✅ catch specific exceptions; re-raise what you can't handle
try: ...
except ValueError as e:
logger.error(e)
raise # re-raise to propagate
✓ Catch SPECIFIC exceptions, not bare except
✓ Don't silently swallow errors (except: pass) — log or handle them
✓ Use finally / context managers (with) for cleanup
✓ Raise meaningful, specific exception types
Sarrafi kaiɗe mara waliya ya zama dole ne don shirye-shirye masu aminci, kuma hanyar Python ta da saurin takaici: tsarin try/except/else/finally, falsafar EAFP (ƙoƙari-da-sarrafi a maimakon bincika-farko, wanda yafi Pythonic kuma ya guje iska-yanayi), kama kaiɗe na musamman (ba gida except, wanda ke boye ɓataye), da amfani da finally/context managers don tsarkakewa.
Ganin waɗannan abubuwan ya hana jide-jide daga kaiɗe da ba su da sarrafa da kuma matsanancin abubuwan da aka tsantsa wajen sarrafi kaiɗe masu wayo ko kashewa — tushe na yau da kullun na shirye-shiryen da ba aminci.