简体   繁体   English

在Python中有什么用于raise foo,bar的用例吗?

[英]Are there any use cases for raise foo, bar in Python?

Python 2 supports the following syntax for raise : Python 2中支持以下语法raise

raise FooException(bar) # call
raise FooException, bar # positional

I thought that the positional syntax was just a historical result of old Python supporting arbitrary values as exceptions. 我认为位置语法只是旧Python支持任意值作为异常的历史结果。

Are there any use cases for the positional syntax that can't be done (or are more verbose) with the call syntax? 是否存在使用调用语法无法完成(或更详细)的位置语法的用例?

I'm addressing the edited version of the question in my answer, mainly 我主要在答案中解决问题的编辑版本

However, even Python 3 considers raise Foo() and raise Foo to be equivalent. 然而,即使Python 3也考虑提高Foo()并将Foo提升为等价。

The "call" syntax ( raise Foo(obj) ) will assign arbitrary object obj to the Exception object's args tuple attribute. “call”语法( raise Foo(obj) )将任意对象obj分配给Exception对象的args tuple属性。 While any object can be used as obj , this is mainly used for custom strings: 虽然任何对象都可以用作obj ,但这主要用于自定义字符串:

try:
    raise ValueError('a custom string')
except ValueError as e:
    print(e.args[0])
    # 'a custom string'
    print(e.args)
    # ('a custom string',)

This args tuple is actually used when printing the exception object, so it is pretty handy for logging: 这个args元组实际上是在打印异常对象时使用的,所以它对于日志记录非常方便:

 try:
     raise ValueError('custom error', 2)
except ValueError as e:
    print(e)
    # ('custom error', 2)

raise ValueError() assigns an empty tuple to exc_obj.args , so does raise ValueError . raise ValueError()exc_obj.args分配一个空元组,因此raise ValueError

This even works with multiple objects. 这甚至适用于多个对象。 In this case we will get a tuple of same length: 在这种情况下,我们将得到一个相同长度的元组:

try:
    raise ValueError(1, 2, 3, 4)
except ValueError as e:
    print(e.args)
    # (1, 2, 3, 4)

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

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