0

Hi I have a function that parses the first 60 lines in a file and is supposed to alert a user if there are lines that are entirely whitespace. However these can occur anywhere in those 60 lines so I want the script to parse the entire 60 lines mainly because I need data from a couple of the lines for my error reporting. And we might want to know where those errors occur in the future. I wrote this:

def header_data(data):
    dictionary = {}
    datalen = len(data)
    itrcntr = 0
    try:
        for line in data:
            itrcntr += 1
            if line.isspace():
                raise Exception('File has badly formatted header data line(s)')
            else:
                linesplit = line.rstrip().split(":")
                if len(linesplit) > 1:
                    dictionary[linesplit[0]] = linesplit[1].strip()
        return dictionary 
    except Exception as e:
        errmsg = str(e)
        if itrcntr == datalen:
            return (dictionary, errmsg)
        else:
            pass
  

With this function, I'd expect if it sees that itrcntr is not equal datalen, it would pass and go back to the try block and move on to the next line. But this doesn't happen. INstead it breaks out of the function and continues in the next line in the function caller. How can I make it continue looping till it reaches to the end of the loop in which it will then return the dictionary along with the error message? Or can this not be done with try catch exception handlers?

1
  • You're capturing the exception outside of the loop. The else: pass is a no-op. I think your design is flawed, which is probably the primary cause of your question, but that's a discussion for another day. The answer by @little_birdie is fairly good assuming you're going to retain your flawed design. Commented Oct 27, 2020 at 3:36

2 Answers 2

5

Unless you want to catch exceptions other than the situation of line.isspace, I wouldn't use a try block at all. Just collect your errors in a list, eg:

errors = []
for line in data:
    itrcntr += 1
    if line.isspace():
        errors.append('File has badly formatted header data at line %d.' % itrcntr)

# then at the end:
if errors:
    # do something about it...
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the feedback and answer btw
You're welcome. As explained by others, when an exception is raised, it will take you straight from that point out to the end of the enclosing try block. All the code within the try block after the point where the exception is raised is effectively skipped. If you are in a loop and the try block is outside the loop, the loop will be cut short. If you have a loop where you can have something go wrong with one iteration but you want to continue onto the next iteration, you would put your try block inside the loop. But that makes no sense in this current situation.
1

If any exception occurred, try clause will be skipped and except clause will run.

If you raise an exception anywhere in the Try, everything else will be skipped. So if you want the loop to continue, then just don't use Try Except.

Just collect every error message and then return it.

2 Comments

But doesn't the "pass" command at the end tell it to continue on to the next line?
@edo101 yes, continue to your next line outside of the try block

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.