Search code examples
pythonpython-2.7custom-exceptions

Python custom exception and sub-exceptions


What is a good way of raising sub-exceptions (is that's the term)? Scenario: I want to raise a custom ConnectivityException when http or ftp exception occurs. Is there any way to raise ConnectivityException such that exceptions are categorized properly (i.e. I should be able to tell if ConnectivityException is raised because of http ot ftp)?


Solution

  • A standard technique would be to subclass ConnectivityException to create exception classes specific to each kind of error condition:

    class ConnectivityException(Exception): pass
    
    class HTTPConnectivityException(ConnectivityException): pass
    
    class FTPConnectivityException(ConnectivityException): pass
    

    Then instead of raise ConnectivityException you can use raise HTTPConnectivityException or raise FTPConnectivityException, depending on which specific type of error you want to indicate.

    Multiple exception blocks can be used to dispatch error handling according to the exception type:

    try:
        some_network_operation()
    except HTTPConnectivityException as ex:
        # This will execute if the error is an HTTPConnectivityException.
    except FTPConnectivityException as ex:
        # Likewise for FTPConnectivityException.
    except ConnectivityException as ex:
        # The generic case; this block will execute if the ConnectivityException isn't 
        # an instance of one of the earlier specified subclasses.
    

    Note that the exception-handling blocks are tried in lexical order; the first block specifying a class to which the exception object belongs will be used. In this case, that means that you need to put the ConnectivityException block last, or else it will catch HTTPConnectivityException and FTPConnectivityException as well.