Why raising a tuple works if first element is an Exception?

后端 未结 3 1349
一生所求
一生所求 2021-02-02 10:46

I have a hard time figuring this one out, it\'s about mistakes that can be done when raising an exception in Python 2.7:

try:
  raise [1, 2, 3, 4]
except Excepti         


        
3条回答
  •  失恋的感觉
    2021-02-02 11:32

    http://docs.python.org/reference/simple_stmts.html#the-raise-statement

    "raise" [expression ["," expression ["," expression]]]

    If no expressions are present, raise re-raises the last exception that was active in the current scope... Otherwise, raise evaluates the expressions to get three objects, using None as the value of omitted expressions. The first two objects are used to determine the type and value of the exception.

    Actually, I thought python does tuple unpacking here

    try:
        raise (ValueError, "foo", ), "bar"
    except Exception as e:
        print e.message # foo or bar?
    

    but if it did, the result would be "foo", and not "bar". This behavior doesn't appear to be documented anywhere, there's only a short note about it being dropped in py3:

    In Python 2, the following raise statement is legal

    raise ((E1, (E2, E3)), E4), V

    The interpreter will take the tuple's first element as the exception type (recursively), making the above fully equivalent to

    raise E1, V

    As of Python 3.0, support for raising tuples like this will be dropped. This change will bring raise statements into line with the throw() method on generator objects, which already disallows this.

    http://www.python.org/dev/peps/pep-3109/#id17

提交回复
热议问题