1

How to get line number of exception in Python?


The output of the following code

try:
    print("a" + 1)
except Exception as error_message:
    print("There was an error: " + str(error_message))

is

There was an error: can only concatenate str (not "int") to str

But instead of just printing the

"There was an error: " + str(error_message)

how to print the line number as well like this example

try:
    print("a" + 1)
except Exception as error_message and linenumber as linenumber:
    print("There was an error: " + str(error_message) + ". The line where the code failed was " + str(linenumber))

with the expected output of

There was an error: can only concatenate str (not "int") to str. The line where the code failed was 2

This would be really useful for me when debugging my projects

root
  • 105
  • 1
  • 12
  • I know there are similar question out there, but I couldn't find a solution by looking or trying them out. – root Feb 13 '21 at 16:20
  • 2
    You might want to look at the standard way of formatting tracebacks: https://docs.python.org/3/library/traceback.html – deceze Feb 13 '21 at 16:22
  • 1
    use traceback module. U can try `traceback.print_tb(error_message.__traceback__)` – SURYA TEJA Feb 13 '21 at 16:34

1 Answers1

6
import traceback

try:
    print("a" + 1)
except Exception as e:
    print("There was an error: " + e.args[0] + ". The line where the code failed was " + str(traceback.extract_stack()[-1][1]))
craftman2868
  • 111
  • 2
  • 6
    While this code may provide a solution to the question, it's better to add context as to why/how it works. This can help future users learn and eventually apply that knowledge to their own code. You are also likely to have positive-feedback/upvotes from users, when the code is explained. – Amit Verma Feb 13 '21 at 19:13
  • This doesn't work. It seems to report the line where the exception was caught, not where it was raised. – NeilG Jul 12 '23 at 01:37
  • @NeilG just do traceback.print_exc() – SpicyCatGames Aug 24 '23 at 09:34
  • That's what everyone says @SpicyCatGames. I don't know why everyone automatically thinks everyone wants to print to console. I don't. I want to capture the error information in my own structures so I can report it later. – NeilG Aug 25 '23 at 01:48
  • @NeilG traceback.format_exc() will give you a string. See also https://docs.python.org/3/library/sys.html#sys.exc_info – SpicyCatGames Aug 26 '23 at 02:16
  • @SpicyCatGames, I want the separate pieces so I can manipulate them and apply custom formatting. I found the associated "duplicate" question referred to above provided better answers: https://stackoverflow.com/questions/1278705/when-i-catch-an-exception-how-do-i-get-the-type-file-and-line-number – NeilG Aug 29 '23 at 06:04