Takkun
Takkun

Reputation: 8659

How to pass a variable to an exception when raised and retrieve it when excepted?

Right now I just have a blank exception class. I was wondering how I can give it a variable when it gets raised and then retrieve that variable when I handle it in the try...except.

class ExampleException (Exception):
    pass

Upvotes: 50

Views: 41903

Answers (2)

Fred Foo
Fred Foo

Reputation: 363547

Give its constructor an argument, store that as an attribute, then retrieve it in the except clause:

class FooException(Exception):
    def __init__(self, foo):
        self.foo = foo

try:
    raise FooException("Foo!")
except FooException as e:
    print e.foo

Upvotes: 78

S.Lott
S.Lott

Reputation: 391848

You can do this.

try:
    ex = ExampleException()
    ex.my_variable= "some value"
    raise ex
except ExampleException, e:
    print( e.my_variable )

Works fine.

Upvotes: -4

Related Questions