在函数内尝试除外-跳到函数末尾
我有一个按计划每分钟运行一次的函数。第一步是从 API 中提取数据。有时这有效,有时它超时。如果它有效,我想对数据做一堆事情然后保存它。如果它不起作用,我只想跳到函数的末尾而不做任何事情。所以这是它的工作原理:
def job():
try:
a = requests.get("API address that sometimes work and sometimes doesn't")
except:
print('connection error')
#a bunch of code that transforms the data and then saves it
这是调度程序:
schedule.every().minute.at(":01").do(job)
while 1:
schedule.run_pending()
time.sleep(1)
我可以通过将#a bunch of code线移到 try 中来实现我想要的,但是其他潜在的错误也将被捕获在“连接错误”中。
有没有办法让异常跳到函数的末尾?然后因为它在一分钟的调度程序上它只是稍后再试?
我知道它不是可重复的代码,但这很简单,没有必要。
回答
您可以简单地使用return.
def job():
try:
a = requests.get("API address that sometimes work and sometimes doesn't")
except:
print('connection error')
return