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

前端 未结 2 880
太阳男子
太阳男子 2021-02-03 19:25

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...exc

相关标签:
2条回答
  • 2021-02-03 19:52

    You can do this.

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

    Works fine.

    0 讨论(0)
  • 2021-02-03 20:00

    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
    
    0 讨论(0)
提交回复
热议问题