Python's documentation says:
If no expressions are present,
raise
re-raises the last exception that was active in the current scope.
(Python 3: https://docs.python.org/3/reference/simple_stmts.html#raise; Python 2.7: https://docs.python.org/2.7/reference/simple_stmts.html#raise.)
However, the notion of "last active" seems to have changed. Witness the following code sample:
#
from __future__ import print_function
import sys
print('Python version =', sys.version)
try:
raise Exception('EXPECTED')
except:
try:
raise Exception('UNEXPECTED')
except:
pass
raise # re-raises UNEXPECTED for Python 2, and re-raises EXPECTED for Python 3
which results in something I didn't expect with Python 2:
Python version = 2.7.15 (v2.7.15:ca079a3ea3, Apr 30 2018, 16:30:26) [MSC v.1500 64 bit (AMD64)]
Traceback (most recent call last):
File "./x", line 10, in <module>
raise Exception('UNEXPECTED')
Exception: UNEXPECTED
but has the expected (by me) result with Python 3:
Python version = 3.6.8 (default, Feb 14 2019, 22:09:48)
[GCC 7.4.0]
Traceback (most recent call last):
File "./x", line 7, in <module>
raise Exception('EXPECTED')
Exception: EXPECTED
and
Python version = 3.7.2 (tags/v3.7.2:9a3ffc0492, Dec 23 2018, 23:09:28) [MSC v.1916 64 bit (AMD64)]
Traceback (most recent call last):
File "./x", line 7, in <module>
raise Exception('EXPECTED')
Exception: EXPECTED
So what does "the last ... active" mean? Is there some documentation on this breaking change? Or is this a Python 2 bug?
And more importantly: What is the best way to make this work in Python 2? (Preferably such that the code will keep working in Python 3.)
Note that if one changes the code to
#
from __future__ import print_function
import sys
print('Python version =', sys.version)
def f():
try:
raise Exception('UNEXPECTED')
except:
pass
try:
raise Exception('EXPECTED')
except:
f()
raise # always raises EXPECTED
then things start to work for Python 2 as well:
Python version = 2.7.15 (v2.7.15:ca079a3ea3, Apr 30 2018, 16:30:26) [MSC v.1500 64 bit (AMD64)]
Traceback (most recent call last):
File "./x", line 13, in <module>
raise Exception('EXPECTED')
Exception: EXPECTED
I'm considering to switch to that...