条件检查与异常处理

Aid*_*tis 16 python error-handling exception conditional-statements

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

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

# 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"
Run Code Online (Sandbox Code Playgroud)

这是相同的功能,避免使用异常

# 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"
Run Code Online (Sandbox Code Playgroud)

我认为使用条件总是更易读和易于管理.还是我错了?定义引发异常的API的原因是什么?为什么?

Joc*_*zel 9

例外更易于管理,因为它们定义了可能出错的一般事物.在您的示例中,只有一个可能的问题,因此使用异常没有任何优势.但是如果你有另一个分裂的阶级,那么它需要发出信号表明你不能偏离零.简单地返回None将不再起作用.

另一方面,异常可以是子类,您可以捕获特定的异常,具体取决于您对底层问题的关注程度.例如,您可以有一个DoesntCompute基本异常和子类,如InvalidTypeInvalidArgument.如果您只想要一个结果,您可以将所有计算包装在一个捕获的块中DoesntCompute,但您仍然可以轻松地执行非常具体的错误处理.


Dev*_*inB 6

通常,您希望对可理解,预期和能够处理的情况使用条件检查.对于不连贯或不可处理的案例,您可以使用例外.

所以,如果你想到你的"添加"功能.它永远不应该返回null.这不是添加两件事的连贯结果.在这种情况下,有在被传递和功能应该是参数的误差不会试图假装一切都没有问题.这是抛出异常的完美案例.

您可能希望使用条件检查,如果您处于常规或正常执行情况,则返回null.例如,IsEqual使用条件可能是一个好例子,如果你的一个条件失败,则返回false.IE

function bool IsEqual(obj a, obj b)
{ 
   if(a is null) return false;
   if(b is null) return false;
   if(a.Type != b.Type) return false;

   bool result = false;
   //Do custom IsEqual comparison code
   return result;
}
Run Code Online (Sandbox Code Playgroud)

在这种情况下,对于异常情况和"对象不等于大小写",您都返回false.这意味着消费者(主叫方)无法判断比较是否失败或者对象是否完全不相等.如果需要区分这些情况,那么您应该使用例外而不是条件.

最后,您想要问问自己,消费者是否能够专门处理您遇到的失败案例.如果你的方法/函数不能做它需要做的事情,那么你可能想要抛出异常.