[英]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?
这样做的正确的标准python异常是什么? 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.). PS:我在Python中寻找标准异常的列表,但所有列表似乎只包含相当低级别的异常(如内存异常,算术异常等)。 Are there no high level standard exceptions in Python?
Python中没有高级标准例外吗?
ValueError
seems to be appropriate. ValueError
似乎是适当的。 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
然后使用
raise InvalidState
提高它
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.