python-ldap 的异常是否按层次结构组织?
我有这样的代码:
try:
....
l.simple_bind_s(user, password)
except ldap.CONNECT_ERROR, e:
sys.exit(1)
except ldap.BUSY, e:
sys.exit(2)
except ldap.OPT_NETWORK_TIMEOUT, e:
sys.exit(3)
except ldap.TIMEOUT, e:
sys.exit(4)
except ldap.SERVER_DOWN, e:
sys.exit(5)
我试图捕获各种异常。然而,所有异常都属于 SERVER_DOWN。例如,当出现超时异常时,它会陷入 SERVER_DOWN 异常等。我想知道是否存在类似异常层次结构的东西,这就是为什么它总是陷入 SERVER_DOWN 状态。或者这段代码还有其他问题吗?对于这个问题你有什么看法吗? 提前致谢。
I have a code like this:
try:
....
l.simple_bind_s(user, password)
except ldap.CONNECT_ERROR, e:
sys.exit(1)
except ldap.BUSY, e:
sys.exit(2)
except ldap.OPT_NETWORK_TIMEOUT, e:
sys.exit(3)
except ldap.TIMEOUT, e:
sys.exit(4)
except ldap.SERVER_DOWN, e:
sys.exit(5)
I am trying to catch various kinds of exceptions. However all exceptions fall in SERVER_DOWN. When, for example, there is a timeout exception it falls into SERVER_DOWN exception, etc. I wonder if there is something like a hierarchy of exceptions and that's why it always falls into SERVER_DOWN state. Or is there any other problem with this code? Do you have any opinion about this issue?
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,异常有层次结构,您应该始终开始捕获更具体的异常,最后捕获更广泛的异常。层次结构通常由继承决定。
在您的情况下,由于您最后捕获该异常,所以应该是因为您首先捕获的超时异常引用了另一个包或命名空间。您捕获的最后一个异常是其他异常的超类。
Yes there is a hierarchy of exceptions, you should always start catching the more specific exceptions and finally catch the broader exceptions. The hierarchy is usually determined by Inheritance.
In your case since you are catching that exception last, it should be because the timeout exception you are catching first is refering to another package or namespace. And the last exception you are catching is a super class of the other exceptions.
如果
issubclass(type(raised),named_in_ except_clause)
,则将触发 except 子句。因此,如果引发“is a”ldap.SERVER_DOWN
的异常,并且它不是前面的 except 子句中的任何异常,则将触发最后一个 except 子句。 LDAP 文档 似乎没有提及任何有关层次结构的内容LDAP 特定的异常,但您始终可以在 REPL 中探索它。If
issubclass(type(raised), named_in_except_clause)
, the except clause will trigger. So if an exceptions that "is a"ldap.SERVER_DOWN
is raised and it's none of the exceptions in the previous except clauses, the last except clause will trigger. The LDAP documentation doesn't seem to say anything about the hierachy of the LDAP-specific exceptions, but you could always explore it at the REPL.