创建自己的异常,并提高该相反:
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