我想知道关于不带参数引发异常的最佳实践。 在官方 python 文档中,您可以看到:
try:
raise KeyboardInterrupt
(http://docs.python.org/tutorial/errors.html 第 8.6 章)
在一些不同的代码中,比如 Django 或 Google 代码,你可以看到:
def AuthenticateAndRun(self, username, password, args):
raise NotImplementedError()
( http://code.google.com/p/neatx/source/browse/trunk/neatx/lib/auth.py )
异常在没有参数的情况下被引发之前被实例化。 不带参数实例化异常的目的是什么?什么时候应该使用第一种情况或第二种情况?
提前致谢 法比安
最佳答案
您可以使用任何您喜欢的形式。没有真正的区别,两者在 Python 2 和 3 中都是合法的。Python style guide没有具体说明推荐哪一个。
关于“类形式”支持的更多信息:
try:
raise KeyboardInterrupt
这种形式在 Python 2 和 3 中都是完全合法的。 摘自pep-3109 :
raise EXCEPTION is used to raise a new exception. This form has two sub-variants: EXCEPTION may be an exception class or an instance of an exception class; valid exception classes are BaseException and its subclasses [5]. If EXCEPTION is a subclass, it will be called with no arguments to obtain an exception instance.
Python documentation 中也有描述:
... If it is a class, the exception instance will be obtained when needed by instantiating the class with no arguments.
关于Python,不带参数引发异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3228591/