简体   繁体   中英

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

Python 2 supports the following syntax for 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.

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.

The "call" syntax ( raise Foo(obj) ) will assign arbitrary object obj to the Exception object's args tuple attribute. While any object can be used as obj , this is mainly used for custom strings:

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:

 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 .

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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