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

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

1 Answer 1

7
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]))
Sign up to request clarification or add additional context in comments.

6 Comments

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.
This doesn't work. It seems to report the line where the exception was caught, not where it was raised.
@NeilG just do traceback.print_exc()
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.
@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: stackoverflow.com/questions/1278705/…
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.