Search code examples
pythonexceptionldapcustom-exceptions

Are python-ldap's exceptions organized in a hierarchy?


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.


Solution

  • 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.