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

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

More than 3 years have passed since last update.

@msrks

Pythonの例外処理

Pythonの例外処理ルール

  • try: 括ったコードを例外処理する
  • except <error-case>: error-caseの例外発生時に実行するブロック
  • except: どんな例外発生時にも実行するブロック
  • else: 例外が発生しなかった場合のみ実行するブロック
  • finally: 例外が発生してもしなくても実行するブロック

サンプルコード

test_exception.py
import sys

zerodiv = len(sys.argv) > 1

try:
    if zerodiv:
        a = 10 / 0
    else:
        a = 10 / 1
    print("answer = {}".format(a))

except ZeroDivisionError as e:
    print("ZeroDivisionError")

else:
    print("else statement")

finally:
    print("finally statement")

実行結果

$ python test_exception.py 
answer = 10
else statement
finally statement
$ python test_exception.py zerodiv
ZeroDivisionError
finally statement
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
5
Help us understand the problem. What are the problem?