【Python】Python ~ 基本編 / 例外処理 ~

■ はじめに

Python の 例外処理 (try 節 など) を学ぶ

目次

【1】try - except - finally
【2】raise
【3】else
【4】contextlib.supress

【1】try - except - finally

例1:ゼロ割

print("Enter")
try:
    number = 0
    answer = 100/number
    print(answer)
except ZeroDivisionError as e:
    print(e)
finally:
    print("End")

例2:標準エラー出力

import traceback, sys

print("Enter")
try:
    number = 0
    answer = 100/number
    print(answer)
except ZeroDivisionError as e:
    print(e)
except Exception as e: # その他すべての例外を捕捉
    #print(traceback.format_exc())
    sys.stderr.write(traceback.format_exc())
finally:
    print("End")

【2】raise

* 意図的に例外を投げる(throw new Exception()的な)

例1:raise

print(1)
try:
    raise Exception("意図的例外")
except Exception as e:
    print("予期せぬエラーが発生しました")
    print(e)
finally:
    print(2)

出力結果

1
予期せぬエラーが発生しました
意図的例外
2

【3】else

(多分、自分では使わないけどPythonの資格で問題としてでてたので)

* try節で例外が発生せず正常終了したあとに行う処理をelse節に指定できる
 => finally は、正常・エラー問わずに実行されるが、else は正常時のみ実行。

* else節とfinally節を同時に使うことも可能

【4】contextlib.supress

* 例外が発生しても無視するのに使用
cf. suppress = 抑圧

* 以下の動画で紹介されてた

https://youtu.be/TTatRa6fjIA?t=2623

API仕様
https://docs.python.org/ja/3/library/contextlib.html#contextlib.suppress

例1:contextlib.supress

from contextlib import suppress


print("Start")
with suppress(Exception):
    # わざとエラーを起こす
    num = 100 / 0

print("End")

出力結果

Start
End

参考文献

https://note.nkmk.me/python-try-except-else-finally/
動画
https://paiza.jp/works/python3/primer/beginner-python10

関連記事

Python ~ 基本編 / 文字列 ~
https://dk521123.hatenablog.com/entry/2019/10/12/075251