470,618 Members | 1,723 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 470,618 developers. It's quick & easy.

Adding to Exception.args

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

Jul 19 '05 #1
1 2115
Andreas Beyer wrote:
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 inp = open(file_name) # GvR prefers this style, not file
try:
for n, line in enumerate(inp):
try:
# parse line ...
except Exception, e:
e.args = e.args + ('line: %d' % (n + 1),) # tuple add
raise
finally:
inp.close() # it is certainly more portable, and more readable

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?


If you are going to play with it, it is more likely that indices
are used (so making e.args[0] refer to the same thing may help).
The __str__ method of the Exception is responsible for formatting.
If you "wrap" an exception that has its own __str__ method, it
may well expect the args tuple to hold a precise number of
elements (and therefore fail to convert to a string).

--Scott David Daniels
Sc***********@Acm.Org
Jul 19 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

2 posts views Thread by Thomas Weholt | last post: by
11 posts views Thread by Steven D'Aprano | last post: by
11 posts views Thread by Russ P. | last post: by
6 posts views Thread by Joel Koltner | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.