0

I tried running these two code snippets

try:
    dict(yyy) # yyy is not a variable
except Exception as e:
    print('ok')

this prints ok as expected.

But then I ran this code

try:
    dict(2 = yyy)
except Exception as e:
    print('ok')

This raises an exception SyntaxError: keyword can't be an expression

But I am catching it and printing ok instead - but it still raises this exception.

So my question is why am I able to cleanly catch an exception in the first code block but not the second code block?

crossvalidator
  • 347
  • 4
  • 10
  • The first code snippet errors at runtime since it's just an undefined variable. The second code snippet errors at compile-time (and thus can't be caught) because python literally cannot parse a number as an identifier. – Aplet123 Sep 02 '21 at 00:59

0 Answers0