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]
2
  • On Python 3 when printing the FlowException you'd get an error like "while handling [original exception stack] encountered FlowException [flow exception stack]" Commented Jan 22, 2018 at 12:54
  • 2
    Possible duplicate of How to print the full traceback without halting the program? Commented Jan 22, 2018 at 12:59

2 Answers 2

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)
Sign up to request clarification or add additional context in comments.

1 Comment

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
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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.