如何获取Python中异常的行号?
以下代码的输出
try:
print("a" + 1)
except Exception as error_message:
print("There was an error: " + str(error_message))
Run Code Online (Sandbox Code Playgroud)
是
There was an error: can only concatenate str (not "int") to str
Run Code Online (Sandbox Code Playgroud)
但不仅仅是打印
"There was an error: " + str(error_message)
Run Code Online (Sandbox Code Playgroud)
如何像这个例子一样打印行号
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))
Run Code Online (Sandbox Code Playgroud)
预期输出为
There was an error: can only concatenate str (not …Run Code Online (Sandbox Code Playgroud)