Black
Black

Reputation: 4644

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;

Upvotes: 0

Views: 3859

Answers (1)

Othrayte
Othrayte

Reputation: 647

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

Upvotes: 2

Related Questions