简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM