beSpark
beSpark

Reputation: 135

Large try except block in Python - how to understand where was an exception?

I have a program (not mine) that has a large try - except block. Somewhere in this block there is an exception. what is the best way to find out the exact string of code where it happens?

Upvotes: 4

Views: 1944

Answers (2)

aIKid
aIKid

Reputation: 28242

Ah, if you don't want an exception to be raised, you can just have the error message, then pass:

>>> try:
    raise ValueError("A stupid error has occurred")
except Exception as e:
    the_error = str(e)
    pass

>>> the_error
'A stupid error has occurred'

Upvotes: 1

thefourtheye
thefourtheye

Reputation: 239443

You can use print_exc in the except block

import traceback
traceback.print_exc()

Example:

import traceback
try:
    pass
    pass
    pass
    pass
    pass
    raise NameError("I dont like your name")
    pass
    pass
    pass
    pass
    pass
except Exception, e:
    traceback.print_exc()

Output

Traceback (most recent call last):
  File "/home/thefourtheye/Desktop/Test.py", line 8, in <module>
    raise NameError("I dont like your name")
NameError: I dont like your name

Upvotes: 7

Related Questions