Make42 Make42 - 4 months ago 34
Python Question

What Python Exception should I raise when illegal state is asked for?

I have an object which state is updated from time to time. After a while I want to ask for the state. However depending on the updates my state might not yet be ready to be asked for. If I ask for the state prematurely I would like to have an Exception raised. What would be the right standard Exception in Python to do that? If there is none - should I write my own?

PS: I looked for lists of standard exceptions in Python, but all lists seem to only contain rather low level exceptions (like memory exceptions, arithmetic exceptions etc.). Are there no high level standard exceptions in Python?


ValueError seems to be appropriate. You can also subclass it.

class InvalidState(ValueError):
    """Exception raised when the state is invalid"""
    def __repr__(self):
        return 'The state is invalid'

Then raise it using raise InvalidState