在 python(内置函数或其他东西)中是否有任何方法可以检查函数执行是否由于错误或工作而失败?并根据情况返回 true 或 false
我期望发生的事情的例子:
内置方法示例:iserror
iserror(float('123')) #returns False, as no error on float('123') occurs
iserror(float('as1f')) #returns True, as it is not possible to convert to float the string ('as1f')
最佳答案
没有这个功能。您无法构建一个函数来满足您的要求,因为在 Python 调用 iserror()
时,float('123')
或 float ('as1f')
表达式已经被执行;如果那里出现异常,则永远不会执行 iserror()
。
您必须将调用委托(delegate)给该函数:
def iserror(func, *args, **kw):
try:
func(*args, **kw)
return False
except Exception:
return True
然后像这样使用它:
iserror(float, '123') # False
iserror(float, 'as1f') # True
然而,捕获所有错误并不是一个好主意。尽管上面的函数试图通过捕获 Exception
来做正确的事情(从而避免捕获 SystemExit
或 KeyboardInterrupt
),它将 捕获 MemoryError
,这表明您内存不足,而不是您测试的函数的参数错误!
始终 try catch 特定 异常;您可以扩展 iserror()
以接受特定的异常:
def iserror(func, *args, **kw):
exception = kw.pop('exception', Exception)
try:
func(*args, **kw)
return False
except exception:
return True
然后只捕获 ValueError
来测试你的 float()
调用:
iserror(float, '123', exception=ValueError) # False
iserror(float, 'as1f', exception=ValueError) # True
这不再那么可读了。无论您想使用可能引发异常的函数调用,我都坚持使用简单的内联 try..except
,因为这样您就可以针对特定异常定制您的响应,而不必自己重复在确定不会出现错误后处理结果:
while True:
value = raw_input('Please give a number: ')
try:
value = int(value)
break
except ValueError:
print "Sorry, {} is not a valid number, try again".format(value)
关于python - 如果函数有效则为真,如果函数出错则为假,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34793339/