Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scope for "raise" without arguments in nested exception handlers in Python 2 and 3

Consider the following minimal example:

try:
  raise Exception('foo')
except Exception:
  try:
    raise Exception('bar')
  except Exception:
    pass
  raise 

Running this code with Python 2 raises exception bar, running it with Python 3 raises exception foo. Yet, the documentation for both Python 2 and Python 3 states that raise with no expression will raise "the last exception that was active in the current scope". Why is the scope different in Python 2 and 3? Is the difference documented anywhere?

like image 249
a3nm Avatar asked Feb 24 '15 14:02

a3nm


1 Answers

The scopes are different because Python 3 is more advanced. :)

The scope for bar starts with the indented try, and ends after the last statement in its except clause (or finally clause had there been one); the bare raise is clearly in the foo except stanza, and that is what is reraised.

This is one of those little things that was fixed in Python 3. The docs could be clearer, though.

like image 182
Ethan Furman Avatar answered Oct 14 '22 21:10

Ethan Furman