Adding to Exception.args

Andreas Beyer beyer at imb-jena.de
Mon Jun 13 14:32:25 EDT 2005


Hi,

If an exception gets raised while I am parsing an input file I would 
like to know where (in which line) the error occured. I do not want to 
create my own exception class for that purpose and I also do not want to 
deal with all possible kinds of exceptions that might occur.

I came up with the following code:

    inp = file(file_name)
    for n, line in enumerate(inp):
        try:
            # parse line ...
        except Exception, e:
            inp.close() # Is this necessary for 'r' files?
            args = list(e.args)
            args.insert(0, 'line: %d'%(n+1))
            e.args = tuple(args)
            raise

Which looks like this in the traceback:

   ValueError: ('line: 3', 'invalid literal for float(): not_a_number')

Is this the 'correct' way to do that?
Is there any specific order to the arguments in e.args? Should my 'user 
argument' be at the beginning or at the end of e.args?

Thanks!  Andreas






More information about the Python-list mailing list