Naggappan Ramukannan
Naggappan Ramukannan

Reputation: 2822

Is there any way to capture exact line number where exception happened in python

Hi is there any way to get the exact line number where the exception happen? because i am using a wrapper method and in actual method there are many lines of code and i am getting a very generic exception and not sure where exactly it is happening . Eg code as below,

import sys
def test(**kwargs):
    print (kwargs)
    abc

def wraper_test(**kwargs):
    try:
        test(**kwargs)
    except Exception as e:
        exception_type, exception_object, exception_traceback = sys.exc_info()
        print(exception_object.tfline_no)

wraper_test(hello="test", value="lsdf")

Now in the exception line number what i am getting is for test(**kwargs) and not the exact location where the exception is generated in this case "abc" which is inside the test method.

Is there any way to capture the exact line number in exception when we are using wrapper method ?

Upvotes: 3

Views: 860

Answers (1)

JRose
JRose

Reputation: 1432

Try this: the traceback library allows you to get a longer stack trace with more line numbers (this shows the real error is on line 5).

import sys, traceback

def test(**kwargs):
    print (kwargs)
    abc

def wrapper_test(**kwargs):
    try:
        test(**kwargs)
    except Exception as e:
        exception_type, exception_object, exception_traceback = sys.exc_info()
        traceback.print_tb(exception_traceback, limit=2, file=sys.stdout)

wrapper_test(hello="test", value="lsdf")

Upvotes: 4

Related Questions