Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What error to raise when class state is invalid?

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()")?

like image 338
Justin Avatar asked May 23 '12 19:05

Justin


People also ask

What are the 3 types of errors in Python?

There are mainly three kinds of distinguishable errors in Python: syntax errors, exceptions and logical errors.

How do you raise exception 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.

Is TypeError a runtime error?

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.

What is raise value error?

Python ValueError is raised when a function receives an argument of the correct type but an inappropriate value.


1 Answers

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?

like image 193
Daenyth Avatar answered Oct 15 '22 00:10

Daenyth