Pass a dictionary in try/except clause

Meh*_*are 3 python python-3.x

I have a use case that requires passing a dictionary in a try/exception clause in Python 3.x

The error message can be accessed as a string using str() function, but I can't figure out who to get it as a dictionary.

try:
    raise RuntimeError({'a':2})
except Exception as e:
    error = e
    print(error['a'])
Run Code Online (Sandbox Code Playgroud)

e is a RuntimeError object and I can't find any method that returns the message in its original format.

wim*_*wim 8

Exceptions store their init args in an "args" attribute:

try: 
    raise RuntimeError({'a':2}) 
except Exception as e: 
    (the_dict,) = e.args 
    print(the_dict["a"])
Run Code Online (Sandbox Code Playgroud)

话虽如此,如果您想要一个具有关联结构化键/值上下文的异常类型,最好为此目的定义您自己的自定义异常子类,而不是RuntimeError直接重用标准库。这是因为如果您捕捉到这样的异常并尝试解压字典上下文,您将需要以RuntimeError不同于RuntimeError标准库可能引发的实例的方式检测和处理您的实例。完全使用不同的类型将使在代码中区分这两种情况更加清晰和容易。