什么是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/