简体   繁体   English

尝试除了在 function 内 - 跳到 function 的末尾

[英]try except inside a function - skip to end of function

I have a function that is on a schedule to run every minute.我有一个按计划每分钟运行一次的 function。 The first step is to pull data from an API.第一步是从 API 中提取数据。 Sometimes this works and sometimes it times out.有时这有效,有时它会超时。 If it works, I want to do a bunch of stuff to the data and then save it.如果它有效,我想对数据做一堆东西然后保存它。 If it doesn't work, I just want to skip to the end of the function and not do anything.如果它不起作用,我只想跳到 function 的末尾而不做任何事情。 So here is how it works:所以这是它的工作原理:

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

and here is the scheduler:这是调度程序:

schedule.every().minute.at(":01").do(job)

while 1:
    schedule.run_pending()
    time.sleep(1)

I can kind of achieve what I want by moving the #a bunch of code line into the try, but then other potential errors are going to be caught in the "connection error" as well.我可以通过将#a bunch of code行移动到try中来实现我想要的,但是其他潜在的错误也会被“连接错误”捕获。

Is there a way where I can make the exception skip to the end of the function?有没有办法让异常跳到 function 的末尾? And then because its on a one minute scheduler it just tries again later?然后因为它在一分钟的调度程序上,它只是稍后再试一次?

I know its not reproducible code but this is simple enough that it shouldn't be necessary.我知道它不可重现的代码,但这很简单,它不应该是必要的。

You can simply use return .您可以简单地使用return

def job():
   try:
      a = requests.get("API address that sometimes work and sometimes doesn't")
   except:
      print('connection error')
      return

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM