48

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
Takkun
  • 8,119
  • 13
  • 38
  • 41

2 Answers2

75

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
Fred Foo
  • 355,277
  • 75
  • 744
  • 836
-3

You can do this.

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

Works fine.

S.Lott
  • 384,516
  • 81
  • 508
  • 779
  • 3
    Although this work, it's not generally a good practice to set object attributes like this. The accepted answer approach of doing this inside `__init__` is better. – Mike N Mar 22 '17 at 13:57