Python raise 有两个参数

标签 python python-2.7 exception

什么是raise A, B做?它与raise A有何不同?是吗?

一些例子(运行在python 2.7的解释器上):

class E(Exception):
    pass
e = E()

raise Exception, e
Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
__main__.E

raise Exception(e)
Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
Exception

raise (Exception, e)
Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
Exception

谢谢!

最佳答案

raise 最多支持三个参数;前两个是类型和值,第三个是用于异常的回溯对象。线路:

raise Exception, value

通常完全等同于:

raise Exception(value)

因此,创建 Exception() 的实例,将第二个值作为参数传递给异常构造函数。

但是,在您的示例中,第二个参数是 E 类型的实例,它是 Exception 的子类,因此行:

raise Exception, e

相当于:

raise e

你也可以在这里使用一个空元组:

raise E, ()

:

raise E, None

只是为了增加引发E 异常类型的方法的数量;元组的第二个参数指定要用于 E 异常类型的所有参数;空元组或 None 等同于 raise E()

至于使用元组 作为第一个参数,这等同于使用raise Exception 作为Python will unwrap nested tuples used as the first argument .

来自raise statement documentation :

If the first object is a class, it becomes the type of the exception. The second object is used to determine the exception value: If it is an instance of the class, the instance becomes the exception value. If the second object is a tuple, it is used as the argument list for the class constructor; if it is None, an empty argument list is used, and any other object is treated as a single argument to the constructor. The instance so created by calling the constructor is used as the exception value.

所有这些规则使语句变得复杂,并且有多种方法可以引发功能等效的异常。因此,多参数 raise 语法已从 Python 3 中完全删除,请参阅 PEP 3109 - Raising Exceptions in Python 3000 .

关于Python raise 有两个参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22921088/

相关文章:

python - 为什么屏幕无法以 Kv 语言加载?

python - 带有(非 unicode)字符串的 PyUnicode_FromFormat

python - 使用 Python 运行复杂的 grep 命令

部署在 Ubuntu/Apache 服务器上时,Django 日志记录不工作

java - 在 Android 中使用 Exception 使应用程序崩溃

php - try{...}catch 在 PHP/Symfony2/PHPImap 中不会引发异常

python - 如果程序在 Python 3 中失败则跳转到脚本末尾

python - 在 Windows 上使用 Python 3.4 64 位构建 VRPN 服务器

python - Matplotlib 散点图在 x 轴上不采用字符串?

python - 使用 Python 抓取 HTML