Locating the line number where an exception occurs in python code

Viewed 22743

I have a code similar to this:

try:
  if x:
      statement1
      statement2
      statement3
  elif y:
      statement4
      statement5
      statement6
  else:
      raise

except:
      statement7

Here, I am sure that the exception occurs in If x: block, but I would like to know in which statement of If x: block the exception occurs. Is there a way to get the line number where the exception occurs?

Regards,

10 Answers

we can get the line number by splitting the string state of the traceback.format_exc(). please try running the following code..

import traceback

try:
    a = "str"
    b = 10

    c = a + b
except Exception as e:
    err_lineno = str(traceback.format_exc()).split(",")[1]
    print(err_lineno)

this will produce the following output

line 7
Related