1

I would like when there is an error that it would display what line the error occurred at. I am unsure how I can obtain the line # that the error happened at though. Any help would be appreciated.

def main():
    while True:
       try:
           function1()
           function2()
           function3()
       except:
           print('error occur at line ' + str(errorline))
1

1 Answer 1

3

Using traceback.extract_tb:

import sys
import traceback
try:
    # Your code
except:
    tb = sys.exc_info()[-1]
    print(traceback.extract_tb(tb, limit=1)[-1][1])

I added limit=1 for efficiency, to avoid loading the (possibly) huge traceback. You can't avoid indexing the list ([-1] to get the last element) though.

Sign up to request clarification or add additional context in comments.

2 Comments

extract_tb takes a limit param that can be used instead of indexing the array. Also, according to the doc, if you store the traceback reference returned by exc_info() you should always delete it or it creates a circular reference that is difficult to garbage collect.
@aruisdante only important in Python 2.

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.