Pre-defining an action to take when an expected error occurs

Steven D'Aprano steve at REMOVEME.cybersource.com.au
Thu Sep 14 23:07:45 EDT 2006


On Thu, 14 Sep 2006 19:40:35 -0700, Tempo wrote:

> Hello. I am getting the error that is displayed below, and I know
> exactly why it occurs. I posted some of my program's code below, and if
> you look at it you will see that the error terminates the program
> pre-maturely. Becasue of this pre-mature termination, the program is
> not able to execute it's final line of code, which is a very important
> line. The last line saves the Excel spreadsheet. So is there a way to
> make sure the last line executes? 

Two methods:

(1) Fix the bug so the program no longer terminates early. You are getting
an IndexError "list index out of range", so fix the program so it no
longer tries to access beyond the end of the list.

I'm guessing that your error is right at the beginning of the loop. You
say:

for rx in range(sh.nrows):
    rx = rx +1

Why are you adding one to the loop variable? That's equivalent to:

for rx in range(1, sh.nrows + 1)

which probably means it skips row 0 and tries to access one row past the
end of sh. If all you want to do is skip row 0, do this instead:

for rx in range(1, sh.nrows)


(2) Stick a band-aid over the error with a try...except block, and hope
you aren't covering up other errors as well. While we're at it, let's
refactor the code a little bit...

# untested
def write_row(rx, sh, end, ws):
    u = str(sh.cell_value(rx, 0))
    if u != end:
        soup = BeautifulSoup(urllib2.urlopen(u))
        p = str(soup.findAll('span', "sale"))
        for row in re.findall('\$\d+\.\d\d', p):
            ws.write(r,0,row)  # what's r? did you mean rx?


Now call this:

for rx in range(sh.nrows):
    rx += 1 # but see my comments above...
    try:
        write_row(rx, sh, end, ws)
    except IndexError:
        pass
w.save('price_list.xls')



-- 
Steven D'Aprano 




More information about the Python-list mailing list