我想修补一个库来捕获内置的 ConnectionError (继承自 OSError)。
到目前为止一切顺利。碰巧的是,该库有一个“自定义”异常,也称为 ConnectionError:
class LibraryError(Exception):
pass
class ConnectionError(LibraryError):
pass
我想,如果我现在 try catch ConnectionError,做类似的事情
try:
do_something()
except ConnectionError as e:
try_to_get_it_right_again()
我只会捕获自定义的 ConnectionError,它继承自 LibraryError。 (免责声明:我必须承认,我自己还没有测试过,因为我不知道怎么做)。
如何让 Python 捕获内置的 ConnectionError?
请您参考如下方法:
使用 builtins module,命名空间的显式名称,其中存在诸如 int 和 ConnectionError 之类的内置名称。
import builtins
try:
...
except builtins.ConnectionError:
...
在 Python 2 中,这将是 __builtin__,尽管 Python 2 没有 ConnectionError。请注意,__builtins__ 本身就是个奇怪的东西;即使它看起来像您想要的,但实际上并非如此。
如果你想要在 Python 2 和 Python 3 中都工作的代码......好吧,异常层次结构在 Python 2 中看起来很不一样,而且 ConnectionError 甚至不存在,所以它不像决定是否使用 builtins 或 __builtin__。 builtins/__builtin__ 至少很容易解决。
要根据 Python 版本导入正确的模块,您可以捕获 ImportError 并导入另一个模块:
try:
import builtins
except ImportError:
import __builtin__ as builtins
暂时假设 Python 2 有 ConnectionError,您可以在隐藏名称之前保存对内置 ConnectionError 的引用:
_builtin_ConnectionError = ConnectionError
class ConnectionError(LibraryError):
...
