Skip to content
Advertisement

How to Catch Exception in for loop and return exception only after loop is done?

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?

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement