Question

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)?

Was it helpful?

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.

OTHER TIPS

you can add an attribute named 'source' to ConnectivityException, and set it to 'http' or 'ftp' according to specific situation, when catch ConnectivityException, check the source attribute and decide what to do

here i recommend another way which uses inherit class

class ConnectivityException(Exception):
    pass # you can define some attributes and methods, here I just escape

class HTTPConnectivityException(ConnectivityException):
    pass

class FTPConnectivityException(ConnectivityException):
    pass

def func():
    if some_condition:
        raise HTTPConnectivityException()
    if some_other_condition:
        raise FTPConnectivityException()

def another_func():
    try:
        func()
    except HTTPConnectivityException as e:
        pass # you can do something here
    except FTPConnectivityException as e:
        pass
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top