Home > Back-end >  Assigning names to errors in except blocks and using them later [duplicate]
Assigning names to errors in except blocks and using them later [duplicate]

Time:09-18

This code snippet works:

try:
    raise Exception('oh no!')
except Exception as e:
    error = e

print(error) # prints "oh no!"

This code snippet fails:

try:
    raise Exception('oh no!')
except Exception as e:
    e = e

print(e) # NameError: name 'e' is not defined

What's going on?

CodePudding user response:

In Python,

except Exception as e:
    error = e

is equivalent to

except Exception as e:
    try:
        error = e
    finally:
        del e

I.e., e is deleted after the except block. If you assign e to e, it will be deleted - however, this is only true for the alias. If you assign it to error, e will also be deleted but not error.

Source: https://docs.python.org/3/reference/compound_stmts.html#the-try-statement

  • Related