【问题标题】:Is there a way to handle exceptions but only from a specific library?有没有办法处理异常,但只能来自特定的库?
【发布时间】:2018-03-23 23:25:37
【问题描述】:

我正在使用一个包 (foo) 并在该包内调用一个类 (Foo) 中的方法。假设包定义了自己的异常:

exception foo.exceptions.FooEx_1
exception foo.exceptions.FooEx_2
...
exception foo.exceptions.FooEx_n

我不想编写通用异常处理程序:

try:
except:
  # Process any exception here

我只想捕获 foo 库/包中引发的异常。有没有办法做到这一点?喜欢:

try:
except foo.exceptions.*

【问题讨论】:

  • 库应该(希望)您是否有礼貌地实现其他人派生的基本异常?
  • 那么它就是:除了 BaseExceptionClass: ?

标签: python python-2.7 exception-handling


【解决方案1】:

如果foo.exceptions 中的所有异常都是某个基类foo.exceptions.BaseFooException 的子类,则可以捕获它:

>>> assert issubclass(NotImplementedError, RuntimeError)
>>>
>>> try:
...     raise NotImplementedError()
... except RuntimeError:
...     print('Caught it')
...
Caught it

否则,您将不得不从模块中提取所有异常:

all_exceptions = tuple(getattr(foo.exceptions, e) for e in dir(foo.exceptions) if e.startswith('FooEx'))

并过滤它们:

try:
    ...
except all_exceptions as e:
    # We caught it

【讨论】:

  • all_exceptions 设为元组并执行except all_exceptions as e 可能更简单。
猜你喜欢
  • 1970-01-01
  • 2023-03-21
  • 2018-02-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多