【发布时间】:2011-02-13 22:31:16
【问题描述】:
什么时候异常处理比条件检查更可取?在很多情况下,我可以选择使用其中的一种。
例如,这是一个使用自定义异常的求和函数:
# module mylibrary
class WrongSummand(Exception):
pass
def sum_(a, b):
""" returns the sum of two summands of the same type """
if type(a) != type(b):
raise WrongSummand("given arguments are not of the same type")
return a + b
# module application using mylibrary
from mylibrary import sum_, WrongSummand
try:
print sum_("A", 5)
except WrongSummand:
print "wrong arguments"
这是同一个函数,避免使用异常
# module mylibrary
def sum_(a, b):
""" returns the sum of two summands if they are both of the same type """
if type(a) == type(b):
return a + b
# module application using mylibrary
from mylibrary import sum_
c = sum_("A", 5)
if c is not None:
print c
else:
print "wrong arguments"
我认为使用条件总是更具可读性和可管理性。还是我错了?定义引发异常的 API 的正确案例是什么?为什么?
【问题讨论】:
-
就像上面 gimel 的链接一样,EAFP 总是比测试类型更可取,因此在编写良好的 Python 中您将很少看到
type(a) == type(b)比较(尽管它们在 C++ 中很常见)。如果 sum 的调用者使用了不兼容的类型,她应该得到一个 TypeError 异常。
标签: python exception error-handling conditional-statements