What is the “proper” exception class to raise when one of my functions detects None passed where an argument value is required? For instance:
def MyFunction(MyArg1, MyArg2):
if not MyArg2:
raise ?Error?
I think I’ve seen TypeError used here (and it’s true that I’m receiving a NoneType where some other type is expected) but that doesn’t strike me as quite right for this situation where I think the Exception could be more explicit.
There is no “invalid argument” or “null pointer” built-in exception in Python. Instead, most functions raise
TypeError(invalid type such asNoneType) orValueError(correct type, but the value is outside of the accepted domain).If your function requires an object of a particular class and gets
Noneinstead, it should probably raiseTypeErroras you pointed out. In this case, you should check forNoneexplicitly, though, since an object of correct type may evaluate to booleanFalseif it implements__nonzero__/__bool__:Python docs:
TypeErrorpython2 / python3ValueErrorpython2 / python3