Python,不带参数引发异常

标签 python exception arguments raise

我想知道关于不带参数引发异常的最佳实践。 在官方 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/

相关文章:

python - Pymongo查询问题

c++ - 使用 SEH(结构化异常处理)时观察到的不同行为

C++ 无法将 public const string 成员作为参数传递给同一类的成员函数

qt - 'QMessageBox::critical':4 个重载中没有一个可以转换所有参数类型

python - 如何拆分逗号和点?

python - 按值作为索引删除列表中的元素

hibernate - 发生异常后如何从 `don' 恢复 t 刷新 session `错误?

javascript - NodeJS 错误处理 - 使用错误代码或子类化

iphone - 如何调用采用可变数量参数的方法的父类(super class)实现,如 [UIAlertView initWithTitle ...]?

Python Turtle对角线长度错误?