jonathan topf
jonathan topf

Reputation: 8367

Store exception body in variable

Is there a way to execute a try statement and return the error body as a variable?

i.e.

var = ''
try:
    error generating code
except:
    var = exception_body

Upvotes: 8

Views: 11900

Answers (1)

Greg Hewgill
Greg Hewgill

Reputation: 992955

Yes, use the as syntax of except:

try:
    raise Exception("hello world")
except Exception as x:
    print(x)

In earlier versions of Python, this would be written except Exception, x: which you may see from time to time.

Upvotes: 18

Related Questions