Pythonにおける例外階層と標準的な捕捉方法

Pythonでは、例外処理をtry...except...else...finally構文で実装する。基本的な構造は以下の通りである:
try:
    # 実行したいコード
    ...
except 特定の例外 as e:
    # 例外発生時の処理
    ...
else:
    # 例外が発生しなかった場合に実行
    ...
finally:
    # 常に実行されるクリーンアップ処理
    ...
例えば、ゼロ除算を安全に処理する関数は次のように書ける:
def safe_divide(a, b):
    try:
        quotient = a / b
    except ZeroDivisionError:
        print("ゼロで割ることはできません!")
    else:
        print("結果:", quotient)
    finally:
        print("終了処理を実行")
予期しない例外を包括的に捕捉する必要がある場合は、すべての組み込み例外の基底クラスであるBaseExceptionを使用できる。ただし、通常のアプリケーションコードでは、このクラスを直接継承したり捕捉したりすべきではない。 ユーザー定義例外を作成する際は、代わりにExceptionクラス(BaseExceptionのサブクラス)を継承することが推奨される。 Pythonの組み込み例外階層は以下のようになっている:
BaseException
 +-- SystemExit
 +-- KeyboardInterrupt
 +-- GeneratorExit
 +-- Exception
      +-- StopIteration
      +-- StopAsyncIteration
      +-- ArithmeticError
      |    +-- FloatingPointError
      |    +-- OverflowError
      |    +-- ZeroDivisionError
      +-- AssertionError
      +-- AttributeError
      +-- BufferError
      +-- EOFError
      +-- ImportError
      |    +-- ModuleNotFoundError
      +-- LookupError
      |    +-- IndexError
      |    +-- KeyError
      +-- MemoryError
      +-- NameError
      |    +-- UnboundLocalError
      +-- OSError
      |    +-- BlockingIOError
      |    +-- ChildProcessError
      |    +-- ConnectionError
      |    |    +-- BrokenPipeError
      |    |    +-- ConnectionAbortedError
      |    |    +-- ConnectionRefusedError
      |    |    +-- ConnectionResetError
      |    +-- FileExistsError
      |    +-- FileNotFoundError
      |    +-- InterruptedError
      |    +-- IsADirectoryError
      |    +-- NotADirectoryError
      |    +-- PermissionError
      |    +-- ProcessLookupError
      |    +-- TimeoutError
      +-- ReferenceError
      +-- RuntimeError
      |    +-- NotImplementedError
      |    +-- RecursionError
      +-- SyntaxError
      |    +-- IndentationError
      |         +-- TabError
      +-- SystemError
      +-- TypeError
      +-- ValueError
      |    +-- UnicodeError
      |         +-- UnicodeDecodeError
      |         +-- UnicodeEncodeError
      |         +-- UnicodeTranslateError
      +-- Warning
           +-- DeprecationWarning
           +-- PendingDeprecationWarning
           +-- RuntimeWarning
           +-- SyntaxWarning
           +-- UserWarning
           +-- FutureWarning
           +-- ImportWarning
           +-- UnicodeWarning
           +-- BytesWarning
           +-- ResourceWarning

タグ: Python 例外処理 BaseException Exception OSError

5月15日 01:50 投稿