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