Thursday, September 7, 2017


LOCATE THE EXACT LINE OF THE EXCEPTION IN PYTHON

If we are annoyed about the exception in the program and if we wanna know the exact 
statement in which the exception occurs , Here below is the sample snippet which help you to find out the same. I have demonstrated using the assert error.

There are two modules which helps you in the process one is the sys module and another is the traceback module , Import "sys" and "traceback" module.

Click here to get the full source code from git.

import traceback as tracebackInstance
import sys as systemInstance

try:
    assert len(listInstance) >= 0
    assert len(listInstance) == 0
  except AssertionError:
      #Piece of Code which can exactly drill down which line number and statement exception
      _, _, tbInstance = systemInstance.exc_info()
      tracebackInstance.print_tb(tbInstance)
      tableInfo = tracebackInstance.extract_tb(tbInstance)
      filename, line, func, text = tableInfo[-1]
      loggingInstance.error('An error occurred on line {} in statement {}'.format(line, text))
      exit(1)

No comments:

Post a Comment