Help us understand the problem. What is going on with this article?

Pythonの例外処理

More than 3 years have passed since last update.

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
msrks
Computer Scienceと物理が好きです
http://msrks.github.io
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
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  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
ユーザーは見つかりませんでした