Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper exception to raise if None encountered as argument

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.

like image 687
Larry Lustig Avatar asked Nov 28 '11 14:11

Larry Lustig


People also ask

What is the exception raised for an error that does not fall in any of the categories?

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.

What is an exception What are the problems if the exception is raised?

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.

Which statement is used to raise an exception?

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.

Is it possible to raise more than one exception at a time?

Strictly speaking you can't raise multiple exceptions but you could raise an object that contains multiple exceptions.


1 Answers

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
like image 145
Ferdinand Beyer Avatar answered Nov 04 '22 16:11

Ferdinand Beyer