简体   繁体   English

如果 None 作为参数遇到,则引发适当的异常

[英]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?当我的一个函数检测到None需要参数值时要引发的“正确”异常类是什么? 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.我想我已经看到这里使用了TypeError (并且确实我收到了一个NoneType而其他类型是预期的)但是对于我认为 Exception 可能更明确的这种情况,这并没有让我感到非常正确。

There is no "invalid argument" or "null pointer" built-in exception in Python. Python 中没有“无效参数”或“空指针”内置异常。 Instead, most functions raise TypeError (invalid type such as NoneType ) or ValueError (correct type, but the value is outside of the accepted domain).相反,大多数函数会引发TypeError (无效类型,例如NoneType )或ValueError (正确类型,但值在接受域之外)。

If your function requires an object of a particular class and gets None instead, it should probably raise TypeError as you pointed out.如果您的函数需要一个特定类的对象并获得None ,则它可能会如您所指出的那样引发TypeError 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__ :但是,在这种情况下,您应该明确检查None ,因为如果实现__nonzero__ / __bool__ ,则正确类型的对象可能会评估为 boolean False

if MyArg2 is None:
    raise TypeError

Python docs : Python 文档

As others have noted, TypeError or ValueError would be natural.正如其他人所指出的, TypeErrorValueError是很自然的。 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.这允许一致处理大量函数的无效参数,同时还为您提供特定函数的更多详细信息。

Most of the python function raises TypeError if None is passed as an argument.如果None作为参数传递,大多数 python 函数都会引发TypeError Take any function say chr(None) and see it raises TypeError .取任何函数说chr(None)并看到它引发TypeError

What about creating and using a simple custom NoneException: (maybe it is worth its 2 lines of code)创建和使用一个简单的自定义 NoneException 怎么样:(也许它的两行代码值得)

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请参阅 Python 文档: https : //pythonbasics.org/try-except/#User-defined-Exceptions

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.这将防止有人向您传递错误的类型,以及处理 None 问题。 It will return an AssertionError , as per the docs. 根据文档,它将返回一个AssertionError

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM