简体   繁体   中英

Python: Rerun try-except loop

I'm trying to rerun a try-except loop each time there is an error and only break when there is no error.

loop = True;
    while loop == True:
        try:
            for i in data_names:
                #do something
        except Exception, e:
            e = str(e)[0:100];
            parse_error_list.append(str(e)[str(e).rindex(':')+2:str(e).rindex(':')+4]);

            if len(e) == 0:
                loop = False;

As a sanity check, will the following allow me to exit the loop if and only if there is no error?

EDIT: Is the answer? If so, is this the most efficient implementation? ...

loop = True;
    while loop:
        try:
            for i in data_names:
                #do something
        except Exception, e:
            e = str(e)[0:100];
            parse_error_list.append(str(e)[str(e).rindex(':')+2:str(e).rindex(':')+4]);

        if e:
            loop = False;

The neatest solution would probably resemble:

while True:
    try:
        for i in data_names:
            #do something
    except Exception, e:
        #log or otherwise handle exception
    else:
        break

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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