LoginSignup
8
5

More than 5 years have passed since last update.

Pythonの例外処理

Posted at

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
8
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
5