How to know the line while catching exception ?

This is the place for queries that don't fit in any of the other categories.

How to know the line while catching exception ?

Postby MichelFJM » Wed May 22, 2013 2:17 pm

Hello

I'm working with Python 2.5.2 (It is at work, I cannot update).
I'm doing a code that read lines in a file and do some treatments (as usual). When a problem occurs, I can have either the line of the code where error occurs or the line of the read file that causes problem.
The two possibilities are :
Code: Select all
#f=open(data.txt) ; lines=f.readlines()
lines=["key1 123\n","key2 error"]
for l in lines :
   try :
     k,value = l.split()
     # ...
     value = float(value)
   except Exception,e :
     print "error with line ",lines.index(l)+1," :",l
     raise e

or
Code: Select all
#f=open(data.txt);lines=f.readlines()
lines=["key1 123\n","key2 error"]
for l in lines :
     k,value = l.split()
     # ...
     value = float(value)

How can I have both ? That is, in this case, I would like to have :
error with line 2 : key2 error
File "test.py", line 7, in <module>
value = float(value)

Thank you.
MichelFJM
 
Posts: 19
Joined: Wed May 22, 2013 1:41 pm

Re: How to know the line while catching exception ?

Postby setrofim » Wed May 22, 2013 3:09 pm

In your first snippet, you get the source line number in the traceback. You can also explicitly extract it from the traceback object using sys.exc_info():
Code: Select all
import sys

lines=["key1 123\n","key2 error"]
for l in lines :
   try :
     k,value = l.split()
     # ...
     value = float(value)
   except Exception,e :
     tb = sys.exc_info()[2]
     message = "error (on line {}) with input line {} : {}"
     print message.format(tb.tb_lineno, lines.index(l)+1, l)
setrofim
 
Posts: 288
Joined: Mon Mar 04, 2013 7:52 pm

Re: How to know the line while catching exception ?

Postby MichelFJM » Thu May 23, 2013 7:10 am

Works great, thanks.
MichelFJM
 
Posts: 19
Joined: Wed May 22, 2013 1:41 pm


Return to General Coding Help

Who is online

Users browsing this forum: Baidu [Spider] and 3 guests