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
  • 972
  • 1
  • 15
  • 37
user1050619
  • 19,822
  • 85
  • 237
  • 413
  • 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
  • 72,016
  • 6
  • 67
  • 89
  • `sys.exc_info()[2].tb_lineno` is the line number inside the exception handler (`try:` block) not always what you want. To get the line where the exception emerged you need to go through the traceback or go directly to the end: `traceback.extract_tb(sys.exc_info()[2])[-1].lineno` – pabouk - Ukraine stay strong Jun 05 '22 at 17:19
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
  • 418
  • 3
  • 10