Proper exception to raise if None encountered as argument

Question:

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.

Asked By: Larry Lustig

||

Answers:

Just use assert:

assert type(MyArg2) == int

Or alternatively:

assert type(MyArg2) != None

This will prevent someone from passing you the wrong type, as well as dealing with the None issue. It will return an AssertionError, as per the docs.

Answered By: Spencer Rathbun

Most of the python function raises TypeError if None is passed as an argument. Take any function say chr(None) and see it raises TypeError.

Answered By: Abhijit

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:

Answered By: Ferdinand Beyer

As others have noted, TypeError or ValueError would be natural. If it doesn’t seem specific enough, you could subclass whichever of the two exceptions is a better fit. This allows consistent handling of invalid arguments for a broad class of functions while also giving you more detail for the particular function.

Answered By: Michael J. Barber

What about creating and using a simple custom NoneException: (maybe it is worth its 2 lines of code)

class NoneError(Exception):
    pass

raise NoneError("Object not constructed. Cannot access a 'None' object.")

See Python documentation:
https://pythonbasics.org/try-except/#User-defined-Exceptions

Answered By: SiL3NC3
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.