简体   繁体   English

当请求非法状态时我应该提出什么Python异常?

[英]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.

相关问题 对于 Python 中的错误/非法参数组合,我应该引发哪个异常? - Which exception should I raise on bad/illegal argument combinations in Python? 我应该为只能调用一次的函数引发python中的哪种标准异常 - What kind of the standard exception in python should I raise for a function which can only be invoked once 我什么时候应该在python中引发LookupError? - When should I raise LookupError in python? 当没有更多元素可以产生时,Python生成器是否应该引发异常? - Should a Python generator raise an exception when there are no more elements to yield? 发生异常时,我应该提出还是冒犯? - When exception occurs should I raise or bubble it up? 当在数据库中找不到对象时,SQLAlchemy模型应引发哪种类型的异常? - What type of Exception should SQLAlchemy model raise when an object is not found in DB? 类状态无效时会引发什么错误? - What error to raise when class state is invalid? 如果我的字典缺少必需的键,我应该提出哪种异常类型? - What exception type should I raise if my dictionary is missing required keys? 单元测试框架在Python中引发了什么异常? - What exception does the unittest framework raise in Python? python函数参数引发什么异常 - What exception to raise for python function arguments
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM