python2.7 - 在python中处理错误时,在执行完except语句下的内容后是否有办法回跳到代码出错的地方继续执行
PHPz
PHPz 2017-04-18 09:57:02
0
2
1216

python2.x

跑一段代码的时候,可能会报错某个错误,如果报错了,只需要进行一些处理,然后再继续执行原来的代码就好。

我目前是用try .. except来处理的,但是像这样只要报错就只会执行except下的代码然后程序结束

如果我加上finally的话,我又不能知道具体出错的是哪句代码(每一句都有可能报错),所以也没办法在finally下面加上后续的代码。

PHPz
PHPz

学习是最好的投资!

reply all(2)
刘奇

What about reducing the granularity of try-catch? Or paste your code for analysis. What you said about continuing to execute the original code after an exception is a bit vague.

【Edit】
After reading the other two answers, they are basically the two ideas I put forward in the comments below. It should be said that everyone’s ideas are basically the same. Modify it here and give me a code plan:

# introduce a new function
# @return: succeed, new_ip
def exec(ip, url):
    try:
        # do what you want to do 
        return True, ip
    except:
        # change your id
        return False, new_ip
        
# your original logics
urls = [url1, url2, ..., url10]
i = 0
ip = ip1
while i <= len(urls):
    succeed, ip = exec(ip, urls[i])
    if succeed:
        i +=1 
黄舟

I just wrote one, which is to generate Access Token的,Access Token数据库中是唯一的,但是生成Access Token的函数不能保证每次生成的Access Token都是不一样的。所以我用了一个很恶心的whileloop. It’s roughly as follows:

while True:
    try:
        access_token = make_token()
        access_token.add_to_db
        break
    except IntegrityError as e:
        if e.orig.args[0] == 1062:
            # 这种情况下,发生了mysql 1062异常,说明数据库中有重复的access token,需要反复生成新的,直至不同
            pass
        else:
            raise e

Not clever, but it works.

Or talk about your business, maybe it doesn’t have to be so disgusting.

Original text of the question: This is a bit more troublesome for me. For example, I need to request 10 URLs in sequence. If the fifth URL is disconnected, an error will be reported, and then I will execute the code below except to change the IP. It is impossible every time Please write a while request, this is simply unreadable

My plan:

def r(uri, data):
    while True:
        try:
            res = requests(uri, data)
            return res
        except:
            change_ip()

This solution should be possible for single-process and single-thread synchronous requests.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template