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

前端 未结 2 881
太阳男子
太阳男子 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 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
    

提交回复
热议问题