As I am sure you are well aware, python, as do most programming languages, comes with built-in exceptions. 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.
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")
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.
There are mainly three kinds of distinguishable errors in Python: syntax errors, exceptions and logical errors.
Built-in exceptions are the exceptions which are available in Java libraries. These exceptions are suitable to explain certain error situations. Below is the list of important built-in exceptions in Java.
The reason to use try/except is when you have a code block to execute that will sometimes run correctly and sometimes not, depending on conditions you can't foresee at the time you're writing the code.
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
EDIT based on your comment:
Documentation 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
.
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