What error to raise when class state is invalid?
exception, python
Solution
`ValueError` is the best thing to raise in this case. For python, you should prefer using the built-in exception types over creating your own. You should only create new exception types when you expect that you will need to catch it and behave very differently than you'd behave when catching the builtin types. In this case, the situation shouldn't arise - you're not expecting to catch this because it would indicate an error in using the class in question. For this it's not worth creating a new type just to make it have another name - that's what the message string that you pass to `ValueError()` is for.
Is it possible to restructure your class so that such an invalid state is not possible?
Problem
In a Python class, what type of error should I raise from an instance method when some of the other attributes of the class must be changed before running that method? I'm coming from a C# background where I would use `InvalidOperationException`, "the exception that is thrown when a method call is invalid for the object's current state", but I couldn't find an equivalent built-in exception in Python. I've been raising `ValueError` ("raised when a built-in operation or function receives an argument that has the right type but an inappropriate value") when the problem is with the function parameters. I suppose this is technically an invalid value for the `self` parameter; is that the right way to treat it? For example, is this idiomatic: `raise ValueError("self.foo must be set before running self.bar()")`?