LoginSignup
2
4

Pythonの例外処理逆引き

Last updated at Posted at 2023-05-23

基本

try:
    foo_bar()
except Exception as e:
    print(str(e))  # エラーメッセージが欲しい場合
try:
    foo_bar()
except Exception:
    print(traceback.format_exc())  # スタックトレースが欲しい場合

例外の再送出

try:
    foo_bar()
except Exception as e:
    print(str(e))
    raise e

例外クラスを変更して再送出

try:
    foo_bar()
except Exception as e:
    raise MyException from e
# !!! ダメな例 !!!
try:
    foo_bar()
except Exception:
    raise MyException("foo_bar")  # 元々のエラー情報が消える
# !!! ダメな例 !!!

例外オブジェクトを使用せずに再送出

try:
    foo_bar()
except Exception:
    print("foo_bar")
    raise
# 以下のように変数に受けても一概にダメとは思わない… が、冗長ではある
try:
    foo_bar()
except Exception as e:
    print("foo_bar")
    raise e

元々の例外オブジェクトを握り潰して再送出

例外オブジェクトがユーザに解析され得るシステムの場合にOS系のエラーを潰す… など。

try:
    foo_bar()
except Exception:
    raise MyException from None

特定の例外のみ処理する

try:
    foo_bar()
except MyException as e:
    print(str(e))
# !!! ダメな例 !!!
try:
    foo_bar()
except MyException as e:
    print(str(e))
except Exception:  # いらない
    raise
# !!! ダメな例 !!!

特定の例外のみ処理せず再送出

try:
    foo_bar()
except MyException:
    raise
except Exception as e:
    print(str(e))

戻り値を返す

try:
    foo_bar()
    return "OK"
except Exception:
    return "Error"
# 戻り値 or 再送出でも同様
try:
    foo_bar()
    return "OK"
except Exception as e:
    print(str(e))
    raise e
# !!! ダメな例 !!!
try:
    foo_bar()
except Exception:
    return "Error"
return "OK"  # 処理の繋がりが離れれば離れるほど可読性が下がる
# !!! ダメな例 !!!

何もしない

foo_bar()
# !!! ダメな例 !!!
try:
    foo_bar()
except Exception:
    raise
# !!! ダメな例 !!!
2
4
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
2
4