0

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;
8
  • The indentation seems to be messed up. Can you please fix the indentation in the code. Commented Feb 11, 2014 at 5:04
  • the only break condition I can see is if the string representation of your exception is 0-length; i.e. never. Also using actual break is a much saner way to break out of a loop than specifying a variable to do it for you. Commented Feb 11, 2014 at 5:04
  • Like the following? 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]); break; Why doesn't len(e) == 0 for no error break the loop? Commented Feb 11, 2014 at 5:10
  • because the except block never happens if there's no exception. You're checking len(e) inside the except block.. Commented Feb 11, 2014 at 5:13
  • 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; Ah right. Would the above work? Commented Feb 11, 2014 at 5:20

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.