条件检查与异常处理 [英] Condition checking vs. Exception handling
问题描述
例如,这是一个使用自定义异常的求和函数:
#module mylibrary
class WrongSummand(Exception):
pass
def sum_(a,b) :
返回两个相同类型的总和的总和
如果type(a)!= type(b):
raise WrongSummand(给定的参数不是相同类型)
返回a + b
#模块应用程序使用mylibrary
从mylibrary导入sum_,WrongSummand
try:
print sum _(A,5)
除了WrongSummand:
打印错误参数
这是相同的功能,避免使用异常
#module mylibrary
def sum_(a,b):
如果类型为$
,则返回两个求和的总和。type(a)== type(b):
返回a + b
#模块应用程序使用mylibrary
从mylibrary导入sum_
c = sum _(A,5)
如果c不是无:
打印c
否则:
打印错误参数
我认为使用条件总是更易读管理。还是我错了?
异常更易于管理,因为它们定义了一般家庭的事情可能会出错。
在你的例子中只有一个可能的问题,所以使用异常没有任何优势。但是,如果你有另一个班级做分工,那么它需要表明你不能偏离零。简单地返回无
将不再工作。
另一方面,异常可以被子类化,你可以捕获具体的例外,取决于你关心的根本问题。例如,你可以有一个 DoesntCompute
基类异常,像 InvalidType
和 InvalidArgument
。如果你只想要一个结果,你可以把所有的计算结果包含在一个块中,这个块可以捕获 DoesntCompute
,但你仍然可以很容易地做出非常具体的错误处理。
When is exception handling more preferable than condition checking? There are many situations where I can choose using one or the other.
For example, this is a summing function which uses a custom exception:
# 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"
And this is the same function, which avoids using exceptions
# 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"
I think that using conditions is always more readable and manageable. Or am I wrong? What are the proper cases for defining APIs which raise exceptions and why?
Exceptions are much more manageable, because they define general families of things that can go wrong.
In your example there is only one possible problem, so there is no advantage to using exceptions. But if you had another class that does division, then it needs to signal that you can't devide by zero. Simply returning None
wouldn't work anymore.
On the other hand, exceptions can be subclassed and you can catch specific exceptions, depending on how much you care about the underlying problem. For example, you could have a DoesntCompute
base exception and subclasses like InvalidType
and InvalidArgument
. If you just want a result, you can wrap all computations in a block that catches DoesntCompute
, but you can still do very specific error handling just as easy.
这篇关于条件检查与异常处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!