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,
I believe the several answers here recommending you manage your
try/except
blocks more tightly are the answer you're looking for. That's a style thing, not a library thing.However, at times we find ourselves in a situation where it's not a style thing, and you really do need the line number to do some other programattic action. If that's what you're asking, you should consider the
traceback
module. You can extract all the information you need about the most recent exception. Thetb_lineno
function will return the line number causing the exception.Newer versions of the traceback plumbing fix the issue prior to 2.3, allowing the code below to work as it was intended: (this is the "right way")
You should run your program in a debugger, such as
pdb
. This will allow you to run your code normally, and then examine the environment when something unexpected like this occurs.Given a script named 'main.py', run it like this:
Then, when your program starts, it will start in the debugger. Type
c
to continue until the next breakpoint (or crash). Then, you can examine the environment by doing things likeprint spam.eggs
. You can also set breakpoints by doingpdb.set_trace()
(I commonly doimport pdb; pdb.set_trace()
).Additionally, what do you mean that it is "okay" for 'statement 3' to raise the exception? Are you expecting the exception? If so, it might be better to write a try/except block around this statement, so that the program can continue.
I've done the following before:
The advantage over printing checkpoints is there's no log output unless there actually is an exception.
we can get the line number by splitting the string state of the
traceback.format_exc()
. please try running the following code..this will produce the following output