Throwing a custom error in a module meant to be imported by arbitrary modules (library)
-
11-10-2019 - |
Question
I'm building a python library that implements a task queue. If for whatever reason the thread that processes the tasks dies, and the option to restart the thread isn't set, I need to throw an exception.
Is this something that I should just throw a RuntimeException
for? I don't want to throw a custom exception since they'd have to import that, but I'm not sure how throw exceptions to arbitrary calling code is best implemented.
Solution
Throw a custom exception. If the user of the library needs to catch that exception, they can import it.
For instance, take pickle.PicklingError
:
>>> import pickle
>>> pickle.dumps(type(None))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python27\lib\pickle.py", line 1374, in dumps
Pickler(file, protocol).dump(obj)
File "C:\Python27\lib\pickle.py", line 224, in dump
self.save(obj)
File "C:\Python27\lib\pickle.py", line 286, in save
f(self, obj) # Call unbound method with explicit self
File "C:\Python27\lib\pickle.py", line 748, in save_global
(obj, module, name))
pickle.PicklingError: Can't pickle <type 'NoneType'>: it's not found as __builtin__.NoneType
>>> try:
... pickle.dumps(type(None))
... except pickle.PicklingError:
... print 'Oops.'
...
Oops.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow