0

Consider the following code:

try:
    a = []
    a[4] = 4
except ZeroDivisionError:
    print('h')
finally:
    print('y')

The output shows that the finally clause was executed:

y
Traceback (most recent call last):
  File "work/finally.py", line 3, in <module>
    a[4] = 4
IndexError: list assignment index out of range

However, if I change the try clause to something like this:

[] += [] - []

Then the finally clause doesn't get executed:

  File "work/finally.py", line 2
    [] += [] - []
    ^
SyntaxError: illegal expression for augmented assignment

What is the reason of this behavior? Where could I read about that? I didn't find it in the docs.

Graipher
  • 6,891
  • 27
  • 47
Henry Barker
  • 784
  • 1
  • 5
  • 9
  • 3
    The reason is that the `try`-clause isn't even entered (which is the condition for the `finally`-block being executed): `SyntaxError`s get raised when trying to parse the file. – L3viathan Dec 10 '18 at 13:05
  • As @ L3viathan said the code is never executed because the SyntaxError occurs while parsing the file. `[] +`= is now allowed, if you want to do a similar thing you could say `lst = [];` and then the `[] +=`. Also be careful because the other part of your statement is not allowed neither – edilio Dec 10 '18 at 13:24

0 Answers0