Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python exception handling - line number

I'm using python to evaluate some measured data. Because of many possible results it is difficult to handle or possible combinations. Sometimes an error happens during the evaluation. It is usually an index error because I get out of range from measured data.

It is very difficult to find out on which place in code the problem happened. It would help a lot if I knew on which line the error was raised. If I use following code:

try:     result = evaluateData(data) except Exception, err:     print ("Error: %s.\n" % str(err)) 

Unfortunately this only tells me that there is and index error. I would like to know more details about the exception (line in code, variable etc.) to find out what happened. Is it possible?

Thank you.

like image 351
JeCh Avatar asked Jan 25 '13 09:01

JeCh


People also ask

How do I print a stack trace in Python?

Print Stack Trace in Python Using traceback Module The traceback. format_exc() method returns a string that contains the information about exception and stack trace entries from the traceback object. We can use the format_exc() method to print the stack trace with the try and except statements.

How do you raise an exception in Python?

As a Python developer you can choose to throw an exception if a condition occurs. To throw (or raise) an exception, use the raise keyword.


1 Answers

Solution, printing filename, linenumber, line itself and exception descrpition:

import linecache import sys  def PrintException():     exc_type, exc_obj, tb = sys.exc_info()     f = tb.tb_frame     lineno = tb.tb_lineno     filename = f.f_code.co_filename     linecache.checkcache(filename)     line = linecache.getline(filename, lineno, f.f_globals)     print 'EXCEPTION IN ({}, LINE {} "{}"): {}'.format(filename, lineno, line.strip(), exc_obj)   try:     print 1/0 except:     PrintException() 

Output:

EXCEPTION IN (D:/Projects/delme3.py, LINE 15 "print 1/0"): integer division or modulo by zero 
like image 155
Apogentus Avatar answered Oct 02 '22 10:10

Apogentus