python函数异常无法捕获

时间:2014-10-10 06:50:13

标签: python function exception parameters

我的代码是这样的:

def retry(func, *args ):
     try:
        func(*args)
     except:
        print "" 

我想编写一个函数来传递函数作为参数,但是在retry函数中,它总是无法捕获传入的函数中的异常。

3 个答案:

答案 0 :(得分:0)

你为什么不这样写:

try:
    func(*args)
except:
    print ""

我确信它可以捕获所有例外情况。

答案 1 :(得分:0)

def retry(func, *args ):
    try: func(*args)
    except SyntaxError: print ""

答案 2 :(得分:0)

如果只是打印一个空字符串,你怎么知道是否输入了except子句?试试这个:

def exception_raising_function(a, b, c):
    print "exception_raising_function(): got args a = {!r}, b = {!r}, c = {!r}".format(a, b, c)
    return 1/0    # raises ZeroDivisionError

def retry(func, *args):
     try:
        return func(*args)
     except Exception as exc:
        print "retry(): got exception %s" % exc

>>> retry(exception_raising_function, 1, 2, 'three')
exception_raising_function(): got args a = 1, b = 2, c = 'three'
retry(): got exception integer division or modulo by zero

这样有用,我们知道它有效,因为有一些输出来证明它。

您似乎想要实现重试函数,如果存在异常,则重试调用函数,即“可重试”异常。您可以使用装饰器执行此操作,类似http://www.saltycrane.com/blog/2009/11/trying-out-retry-decorator-python/中讨论的内容可能对您有用。