Reputation: 1381
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'])
e
is a RuntimeError object and I can't find any method that returns the message in its original format.
Upvotes: 7
Views: 3421
Reputation: 362657
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"])
That being said, if you want an exception type which has a structured key/value context associated, it would be best to define your own custom exception subclass for this purpose rather than re-use the standard library's RuntimeError
directly. That's because if you catch such an exception and attempt to unpack the dictionary context, you would need to detect and handle your RuntimeError
instances differently from RuntimeError
instances that the standard library may have raised. Using a different type entirely will make it much cleaner and easier to distinguish these two cases in your code.
Upvotes: 14