条件检查与异常处理[重复]

发布于 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 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    异常更易于管理,因为它们定义了可能出错的一般事物。在您的示例中,只有一个可能的问题,因此使用异常没有任何好处。但是,如果您有另一个进行除法的类,则它需要发出信号,表明您不能将其除以零。简单地返回None将不再起作用。

    另一方面,可以将异常子类化,并且可以捕获特定的异常,具体取决于您对基础问题的关心程度。例如,您可能有一个DoesntCompute基本异常以及像InvalidType和这样的子类InvalidArgument。如果只想要结果,可以将所有计算包装在catch的块中DoesntCompute,但仍然可以轻松地进行非常具体的错误处理。



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看