Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/302.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
无法捕获python函数异常_Python_Function_Exception_Parameters - Fatal编程技术网

无法捕获python函数异常

无法捕获python函数异常,python,function,exception,parameters,Python,Function,Exception,Parameters,我的代码如下: def retry(func, *args ): try: func(*args) except: print "" try: func(*args) except: print "" 我想编写一个函数,将函数作为参数传递,但在重试函数中,它始终无法捕获传入的函数中的异常。为什么不这样编写: def retry(func, *args ): try: func(*args)

我的代码如下:

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

我想编写一个函数,将函数作为参数传递,但在
重试
函数中,它始终无法捕获传入的函数中的异常。

为什么不这样编写:

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

我确信它可以捕获您的所有异常。

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

def retry(func, *args ):
    try: func(*args)
    except SyntaxError: print ""
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
这是可行的,我们知道这是可行的,因为有一些结果可以证明这一点


您似乎想要实现一个重试函数,该函数在出现异常(即“可重试”异常)时重试调用函数。你可以用一个装饰师来做这件事,就像在上讨论的那样,可能对你有用。

你到底想做什么?您的用例是什么?