2020-07-04
|~1 min read
|146 words
Previously, I wrote about raising custom exceptions, but it was a hamstrung approach. It didn’t actually enable any information to be passed into the exception that might be relayed for further debugging in the logs. Instead, any information that could be reported upon had to be defined above the try/except
block.
In an effort to document my errors better, I sought out how to actually pass along useful information. Well, as I noted in my previous post - custom exceptions are just sub classes, extending the Exception
, which means that to pass along information, we can create a custom initialization, __init__
.
For example:
class MyException(Exception):
def __init__(self, details ):
self.details = details
try:
raise MyException("Useful details to know about the exception!")
except FooException as e:
print e.details
I first learned about this approach from Stack Overflow in this conversation on passing variables to exceptions.
Hi there and thanks for reading! My name's Stephen. I live in Chicago with my wife, Kate, and dog, Finn. Want more? See about and get in touch!