[PYTHON] EP 13 Profitez de chaque bloc dans try / except / else / finally

  • The try/finally cmpound statement lets you run cleanup code regardless of whether exceptions were riased in the try block

Effective Python

try:
# Excute at the beginning

except Exception as e:
# Execute if an exception is riased in try block.

else:
# Execute if try block does not raise exception.
# Allow user to write code which cause exception here in order to propagate exception to upper stack.

finally:
# Executed at the end anyway.

def load_json_key(data, key):
    try:
      result_dict = json.loads(data) # May raise ValueError
    except ValueError as e:
      raise KeyError from e
    else:
      return result_dict[key] # May raise KeyError

Recommended Posts

EP 13 Profitez de chaque bloc dans try / except / else / finally
EP 13 Profitez de chaque bloc dans try / except / else / finally
Impressions de personnes ayant de l'expérience dans d'autres langues apprenant Python à l'aide de PyQ
Tendances des langages de programmation du point de vue de GitHub (mises à jour semestrielles)
python essayez ~ sauf ~ autre
[Texte court] Lors du retour dans les deux clauses try, clause except et clause finally