Python which built in exception to use
Question: As I am sure you are well aware, python, as do most programming languages,
comes with [built-in
exceptions](http://docs.python.org/2/library/exceptions.html). I have gone
through the list, and cannot deduce which would be appropriate. Of course I
can make my own exception, but this is a fairly standard error that would be
excepted.

This is an error based on instance relations. Instances of a class are related
to **only some** of the other instances. Computations can be made depending on
the different connections. This error will be `raise`d if a computation is
attempted on 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

To be honest, it seems like `ValueError` would make most sense because the
value is not allowed, but for some reason this does not fully sit well with
me. The fact that there is no relation is the importance of this error, not
simply the fact that the value attempted is not allowed.

**Is there a better exception than ValueError for my logic?**

note: I understand that this `ValueError` may just be the right answer, but I
am curious if there is something more precise that I may have not been able to
see the connection with when I went through the documentation.


Answer: For me `unrelated instance` sounds like you want to do something with the
instance of wrong type.

What about choosing `TypeError`?

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

[Source](http://docs.python.org/2.7/library/exceptions.html#exceptions.TypeError)

EDIT based on your comment:

[Documentation](http://docs.python.org/2.7/library/exceptions.html#exceptions.TypeError)
says:

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

It is the right type - as you stated in your comment but it has an
inappropriate value. Situation can't be described by `IndexError` => I'd go
for `ValueError`.

