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

John Machin sjmachin at lexicon.net
Thu Sep 14 23:55:54 EDT 2006


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? Thanks in advanced for all of the
> help. Thank you.
>
>
> Error
> ####
>
> IndexError: list index out of range
>
[snip]

Hi, Tempo, nice to see xlrd getting some usage :-)

Are you sure that you *really* want to save a spreadsheet written by
your buggy program??? It is better to fix errors, rather than ignore
them.

However, as you asked how: To ensure that cleanup code is executed no
matter what happens, use try/except/finally as in the following
example.

HTH,
John


C:\junk>type tempo.py
import sys

def main(n):
    return (10 ** n) / n

try:
    try:
        print "executing the application ..."
        n = int(sys.argv[1])
        if n < 0:
            # simulate something nasty happening ...
            import nosuchmodule
        else:
            x = main(n)
        print "app completed normally: %r" % x
    except KeyboardInterrupt:
        # need this to escape when n is large
        print "kbd interrupt ...."
        raise
    except ZeroDivisionError:
        print "doh!"
        raise
finally:
    # code to be executed no matter what happens
    print "finally ... cleaning up"

C:\junk>tempo.py 0
executing the application ...
doh!
finally ... cleaning up
Traceback (most recent call last):
  File "C:\junk\tempo.py", line 14, in ?
    x = main(n)
  File "C:\junk\tempo.py", line 4, in main
    return (10 ** n) / n
ZeroDivisionError: integer division or modulo by zero

C:\junk>tempo.py -1
executing the application ...
finally ... cleaning up
Traceback (most recent call last):
  File "C:\junk\tempo.py", line 12, in ?
    import nosuchmodule
ImportError: No module named nosuchmodule

C:\junk>tempo.py 3
executing the application ...
app completed normally: 333
finally ... cleaning up

C:\junk>tempo.py 10000000000
executing the application ...
kbd interrupt ....
finally ... cleaning up
Traceback (most recent call last):
  File "C:\junk\tempo.py", line 14, in ?
    x = main(n)
  File "C:\junk\tempo.py", line 4, in main
    return (10 ** n) / n
KeyboardInterrupt

C:\junk>




More information about the Python-list mailing list