在模块中抛出自定义错误,意味着由任意模块(库)导入

时间:2010-12-20 01:09:56

标签: python exception exception-handling custom-exceptions

我正在构建一个实现任务队列的python库。如果由于某种原因,处理任务的线程死亡,并且没有设置重启线程的选项,我需要抛出异常。

这是我应该抛出RuntimeException的东西吗?我不想抛出自定义异常,因为他们必须导入它,但我不确定如何最好地实现抛出任意调用代码的异常。

1 个答案:

答案 0 :(得分:2)

抛出自定义异常。如果库的用户需要捕获该异常,他们可以导入它。

例如,取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.