条件检查与异常处理[重复]
发布于 2021-01-29 16:01:08
这个问题已经在这里有了答案 :
在python中使用try vs if
(9答案)
4年前关闭。
什么时候异常处理比条件检查更可取?在许多情况下,我可以选择使用其中一种。
例如,这是一个使用自定义异常的求和函数:
# 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的适当情况是什么?为什么?
关注者
0
被浏览
52
1 个回答