Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
OrganizationEventAdvent CalendarQiitadon (β)
Qiita JobsQiita ZineQiita Blog
Help us understand the problem. What are the problem?

More than 5 years have passed since last update.


EP 13 Take Advantage of Each Block in try/except/else/finally

  • The try/finally cmpound statement lets you run cleanup code regardless of whether exceptions were riased in the try block
  • The else block helps you minimize the amount of code in try blocks and visually ditingush the success case from the try/except blocks
  • An else block can be used to perform additional actions after successful try block but before common cleanup in finally block

Effective Python

# Excute at the beginning

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

# 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.

# Executed at the end anyway.

def load_json_key(data, key):
      result_dict = json.loads(data) # May raise ValueError
    except ValueError as e:
      raise KeyError from e
      return result_dict[key] # May raise KeyError
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Help us understand the problem. What are the problem?