Python which is built in exception to use

As I'm sure, you are well aware that python, like most programming languages, comes with built-in exceptions . I went through the list and cannot deduce what would be appropriate. Of course, I can make my own exception, but this is a pretty standard mistake that will be excluded.

This is an instance relationship based error. Class instances are associated with only a few other instances. Calculations can be made depending on different compounds. This error will raise d if you try to calculate in an unrelated instance.

Example

 class Foo: def __init__(self,related=None): '''related is a list of Foo instances''' if related is not None: self.related = related else: self.related = [] def compute(self,instance): if instance in self.related: #execute code else: raise SomeError("You cannot make a computation with an unrelated instance") 

my thoughts

Honestly, it seems that ValueError will make the most sense because the value is not resolved, but for some reason this does not fully suit me. The fact that there is no relation is the importance of this error, and not just the fact that the value taken is unacceptable.

Is there a better exception than ValueError for my logic?

note: I understand that this ValueError may be the right answer, but I'm curious if there is anything more accurate that I might not be able to see the link when I looked at the documentation.

+6
source share
1 answer

For me, an unrelated instance sounds like you want to do something with an instance of the wrong type.

What about choosing a TypeError ?

Raised when an operation or function is applied to an object of an inappropriate type. The associated value is a string with details about the type mismatch.

A source

EDIT based on your comment:

The documentation reads:

ValueError It is restored when the built-in operation or function receives an argument that has the desired type, but an inappropriate value, and the situation is not described by a more precise exception, such as IndexError.

This is the correct type - as you indicated in your comment, but it has the wrong value. The situation cannot be described IndexError => I would go for ValueError .

+6
source

All Articles