gpt4 book ai didi

python - 条件检查与异常处理

转载 作者:太空狗 更新时间:2023-10-29 16:54:55 24 4
gpt4 key购买 nike

<分区>

什么时候异常处理比条件检查更可取?在很多情况下,我可以选择使用其中一种。

例如,这是一个使用自定义异常的求和函数:

# 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 的正确情况是什么?为什么?

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com