Reputation: 20866
I have defined a custom Exception object and would like to get the line number of the exception.
class FlowException(Exception):
pass
def something():
print 2/3
print 1/2
print 2/0
try:
something()
except Exception as e:
raise FlowException("Process Exception", e)
Now, if there is a exception in something() it throws the FlowException but it does not give me the exact line number, How can I get the line number from FlowException(ie; it failed when it executed 2/0)?
Here is the output:--
raise FlowException("Process Exception", e)
__main__.FlowException: ('Process Exception', ZeroDivisionError('integer division or modulo by zero',))
[Finished in 0.4s with exit code 1]
Upvotes: 5
Views: 8264
Reputation: 418
Tested on Python 3.6
class FlowException(Exception):
pass
def something():
raise ValueError
try:
something()
except Exception as e:
raise FlowException("Process Exception", e)
Output has line numbers:
Traceback (most recent call last):
File "/Users/diman/PycharmProjects/invites/test.py", line 8, in <module>
something()
File "/Users/diman/PycharmProjects/invites/test.py", line 5, in something
raise ValueError
ValueError
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Users/diman/PycharmProjects/invites/test.py", line 10, in <module>
raise FlowException("Process Exception", e)
__main__.FlowException: ('Process Exception', ValueError())
For Python 2 try using internal logger ".exception()" method instead of using monstrous "sys" module.
import logging
logger = logging.getLogger()
try:
something()
except Exception as e:
logger.exception(e)
raise FlowException("Process Exception", e)
Upvotes: 0
Reputation: 73470
The traceback
object holds that info in the tb_lineno
attribute:
import sys
# ...
except Exception as e:
trace_back = sys.exc_info()[2]
line = trace_back.tb_lineno
raise FlowException("Process Exception in line {}".format(line), e)
Upvotes: 6