Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/380.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_Python 3.x - Fatal编程技术网

循环调用Python中的异常绕过

循环调用Python中的异常绕过,python,python-3.x,Python,Python 3.x,我得到了输出,它停止了脚本。即使出现异常错误,是否有任何方法继续运行脚本。坦率地说,我在做一些api调用,而不是x=10/0。但当出现错误时,它会停止脚本。但我想要的是即使有错误也运行脚本,并反复检查。要确保脚本继续运行,即使有错误,请使用try/except块 在块中,除了之外,为了按照查询中的指定,确保代码反复检查错误,您可以使用“函数递归”从函数中再次运行函数: import sys from twisted.internet import reactor, defer, task fro

我得到了输出,它停止了脚本。即使出现异常错误,是否有任何方法继续运行脚本。坦率地说,我在做一些api调用,而不是x=10/0。但当出现错误时,它会停止脚本。但我想要的是即使有错误也运行脚本,并反复检查。

要确保脚本继续运行,即使有错误,请使用
try/except

块中,除了
之外,为了按照查询中的指定,确保代码反复检查错误,您可以使用“函数递归”从函数中再次运行函数:

import sys
from twisted.internet import reactor, defer, task
from twisted.python import log
def periodic_task():
    log.msg("periodic task running")
    x = 10 / 0

def periodic_task_crashed(reason):
    log.err(reason, "periodic_task broken")

log.startLogging(sys.stdout)

my_task = task.LoopingCall(periodic_task)
d = my_task.start(1)
d.addErrback(periodic_task_crashed)
reactor.run()

尽管如此,还是要小心

只需处理验证,使用try。。。除了你知道可能会失败的代码外

def periodic_task():
    log.msg("periodic task running")
    try:
       x = 10 / 0 # include 'API calls' here
    except: # include 'exception type'
       periodic_task()
def periodic_task():
    log.msg("periodic task running")
    try:
        x = 10 / 0
    except Exception as error:
        # Here you should at least log the error, exceptions do not should pass silently.
        pass