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.
Raised when an error does not fall under any other category. Raised by next() function to indicate that there is no further item to be returned by iterator. Raised by parser when syntax error is encountered.
Raising an exception is a technique for interrupting the normal flow of execution in a program, signaling that some exceptional circumstance has arisen, and returning directly to an enclosing part of the program that was designated to react to that circumstance.
The RAISE statement explicitly raises an exception. Outside an exception handler, you must specify the exception name. Inside an exception handler, if you omit the exception name, the RAISE statement reraises the current exception.
Strictly speaking you can't raise multiple exceptions but you could raise an object that contains multiple exceptions.
There is no "invalid argument" or "null pointer" built-in exception in Python. Instead, most functions raise TypeError (invalid type such as NoneType) or ValueError (correct type, but the value is outside of the accepted domain).
If your function requires an object of a particular class and gets None instead, it should probably raise TypeError as you pointed out. In this case, you should check for None explicitly, though, since an object of correct type may evaluate to boolean False if it implements __nonzero__/__bool__:
if MyArg2 is None: raise TypeError Python docs:
TypeError python2 / python3 ValueError python2 / python3 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