5

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]
MehrdadEP
  • 861
  • 1
  • 18
  • 31
user1050619
  • 18,448
  • 72
  • 220
  • 371
  • On Python 3 when printing the `FlowException` you'd get an error like "while handling [original exception stack] encountered FlowException [flow exception stack]" – Bailey Parker Jan 22 '18 at 12:54
  • 2
    Possible duplicate of [How to print the full traceback without halting the program?](https://stackoverflow.com/questions/3702675/how-to-print-the-full-traceback-without-halting-the-program) – Chris_Rands Jan 22 '18 at 12:59

2 Answers2

6

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)
user2390182
  • 67,685
  • 6
  • 55
  • 77
0

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)
Diman
  • 408
  • 3
  • 10