user10870615
user10870615

Reputation:

Suggested Exception type to raise for reaching maximum connection limit

I have a connection manager that works as follows:

def connect(self):
    if len(connections) >= max_connections:
        raise RuntimeError("Cannot initiate new connection.")

Is a RuntimeError the proper error to raise in this circumstance, or what would be a better approach?

Upvotes: 2

Views: 67

Answers (1)

CypherX
CypherX

Reputation: 7353

I think you could use ConnectionError for errors related to connection issues.
In your case, you are looking at something like MaxConnectionLimitReachedError which you could potentially subclass from ConnectionError as follows.

class MaxConnectionLimitReachedError(ConnectionError):
    """
    Exception raised for errors occurring from maximum number 
    of connections limit being reached/exceeded.

    Attributes:
        message -- explanation of the error
        total_connections -- total number of connections when the error occurred (optional)
        max_connections -- maximum number of connections allowed (optional)
    """

    def __init__(self, message, total_connections = None, max_connections = None):
        self.total_connections = total_connections
        self.max_connections = max_connections
        self.message = message

Your use-case would then look like as follows:

def connect(self):
    if len(connections) >= max_connections:
        message = "Maximum connection limit ({}) reached. Cannot initiate new connection."
        raise MaxConnectionLimitReachedError(message.format(max_connections))

Upvotes: 3

Related Questions