創建自己的異常,並提高該相反:
class MyValidationError(Exception):
pass
def my_function():
if not foo():
raise MyValidationError("Error message")
return 4
然後,您可以調用你的函數爲:
try:
result = my_function()
except MyValidationError as exception:
# handle exception here and get error message
print exception.message
這種風格被稱爲EAFP(「易請求原諒比許可」 )這意味着你寫的代碼是正常的,出現異常時會引發異常,並在稍後處理:
This common Python coding style assumes the existence of valid keys or attributes and catches exceptions if the assumption proves false. This clean and fast style is characterized by the presence of many try and except statements. The technique contrasts with the LBYL style common to many other languages such as C.
爲什麼不例外? – 2013-05-08 22:50:57