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()")
?
There are mainly three kinds of distinguishable errors in Python: syntax errors, exceptions and logical errors.
As a Python developer you can choose to throw an exception if a condition occurs. To throw (or raise) an exception, use the raise keyword.
The example at the start of the tutorial, trying to change a character in a string, is an example of a runtime error. This particular one was a TypeError , which is a more specific type of runtime error. Python does have a RuntimeError , which just indicates a generic runtime (non-syntax) error.
Python ValueError is raised when a function receives an argument of the correct type but an inappropriate value.
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With