UNISIA-SE Tech Blog

気まぐれお勉強日記

[Python] [基本] 例外処理と組込み例外クラス

1. 前提条件


このページでは、Pythonの例外処理と組込み例外クラスそれぞれの概要について記載する。

▼ Python3.6がインストールされていること。
このページでは、venvの仮想環境(Python3.6)上にNumPyをインストールした環境で、Python対話モード(Pythonインタプリタ)にて実装サンプルを記載している。

※ Python対話モードについては下記を参考。
Python対話モード:[Python] 対話モード (インタプリタ) の使用方法

2. 例外処理と例外クラス


文字通り 例外(正常系でない想定外のエラー) が発生した場合に対処する処理を 例外処理 と呼び、Pythonでは、メイン処理を try句 に、例外処理を except句 に記載する。

また、except句 に指定する 例外クラス によって、どの例外をキャッチするか指定することができる。

▼ 例外クラス BaseException を指定した場合の構文例

$ python
 >>>
 >>> try:
 ...         # メイン処理を記載…
 >>> except BaseException:
 ...         # BaseExceptionクラスでキャッチした場合の例外処理を記載…
 >>>

ただし、BaseException は、Pythonすべての組込み 例外クラス の派生元(基底)となっており、すべての例外キャッチしてしまうため(ユーザーの妨げになる場合もあるため)、Exception クラス等のキャッチしたい目的に応じた 例外クラス を指定する。

3. 組込み例外クラス一覧


以下、Pythonの組込み 例外クラス とそれぞれの概要。
すべて前項で記載した BaseException から派生する。

例外クラス名 例外キャッチ(except)
タイミング
BaseException任意の組込み例外が発生した場合。
(全組込み例外の基底クラス)
┣ SystemExit システム終了した場合。
(sys.exit()、exit等)
┣ KeyboardInterruptユーザーのキー割込み(Ctrl+C等)が発生した場合。
┣ GeneratorExitジェネレータ 、コルーチンを閉じた場合。(generator.close() 、coroutine.close())
┗ Exceptionシステム終了以外の例外が発生した場合。
(ユーザー定義の例外はここから派生させる。)
 ┣ StopIterationイテレータによる次の領域参照時(next()、イテレータの__next__())、対象が存在しない場合。
 ┣ StopAsyncIteration非同期イテレータによる次の領域参照時(非同期イテレータの__anext__())、対象が存在しない場合。
 ┣ ArithmeticError算術演算で例外が発生した場合。
(以下、OverflowError, ZeroDivisionError, FloatingPointError の基底クラス。)
 ┃┣ FloatingPointError浮動小数点の演算で失敗した場合。※ 3.7以降のバージョンでは使われていないので注意。
(但し、--with-fpectl オプションが有効ある場合、または pyconfig.hにWANT_SIGFPE_HANDLER を定義している場合のみ)
 ┃┣ OverflowError算術演算結果が表現できない値になった場合。
 ┃┗ ZeroDivisionError除算や剰余演算でゼロ割り演算された場合。
 ┣ AssertionErrorassertが失敗した場合。
 ┣ AttributeError属性参照や代入が失敗した場合。
(対象となるオブジェクトが属性参照や代入自体をサポートしていない場合は、TypeErrorとなる。)
 ┣ BufferErrorバッファ関連の操作に失敗した場合。
 ┣ EOFErrorinput()がデータを読み込んでいない状態でend-of-file (EOF)に達した場合。
(io.IOBase.read(),  io.IOBase.readline()は、EOF に達すると空文字列を返す。)
 ┣ ImportErrorimportによるロードが失敗した場合。
(以下、ImportError の基底クラス。)
 ┃┗ ModuleNotFoundErrorimportによるロード時、モジュールが見つからない場合 または sys.modules に None が含まれる場合。
 ┣ LookupErrorマッピング または シーケンスで使われるキーやインデクスが無効な場合
(以下、IndexError, KeyError の基底クラス。)
 ┃┣ IndexErrorシーケンスのインデックスが範囲外の場合。(インデックスが整数でない場合は、TypeErrorとなる。)
 ┃┗ KeyErrorマッピングキー(連想配列キー)が見つからなかった場合。
 ┣ MemoryErrorメモリ不足が発生した場合。
 ┣ NameError存在しないオブジェクト名が指定されている場合。
(以下、UnboundLocalError の基底クラス。)
 ┃┗ UnboundLocalError値が代入されていないローカル変数を参照した場合。
 ┣ OSErrorシステム関数でエラーが発生した場合。
(以下、BlockingIOError ~ TimeoutError の基底クラス。)
 ┃┣ BlockingIOErrorノンブロッキング処理にて処理対象のオブジェクトが事前処理等の準備が整う前に指示がされた場合。
(errno (システムシンボル) EAGAIN, EALREADY, EWOULDBLOCK および EINPROGRESS に対応)
 ┃┣ ChildProcessError子プロセスの操作に失敗した場合。
(errorno (システムシンボル) ECHILD に対応)
 ┃┣ ConnectionErrorコネクション関連の操作に失敗した場合。
(以下、BrokenPipeError~ ConnectionResetErrorの基底クラス。)
 ┃┃┣ BrokenPipeError操作ができないコネクションのパイプ または ソケットを操作した場合。
(errno (システムシンボル) EPIPE, ESHUTDOWN に対応)
 ┃┃┣ ConnectionAbortedError通信先の接続が中断された場合。
(errno (システムシンボル) ECONNABORTED に対応)
 ┃┃┣ ConnectionRefusedError通信先の接続が拒否された場合。
(errno (システムシンボル) ECONNREFUSED に対応)
 ┃┃┗ ConnectionResetError通信先の接続がリセットされた場合。
(errno (システムシンボル) ECONNRESET に対応)
 ┃┣ FileExistsErrorすでに存在するファイル または ディレクトリを作成しようとした場合。
(errno (システムシンボル) EEXIST に対応)
 ┃┣ FileNotFoundError操作対象のファイル または ディレクトリが存在しない場合。
(errno (システムシンボル) ENOENT に対応)
 ┃┣ InterruptedErrorシステムコールが中断された場合。
(errno (システムシンボル) EINTR に対応)
 ┃┣ IsADirectoryError ディレクトリにファイル操作(os.remove() 等)が要求された場合
(errno (システムシンボル) EISDIR に対応)
 ┃┣ NotADirectoryErrorディレクトリ以外にディレクトリ操作(os.listdir() 等)が要求された場合。
(errno (システムシンボル) ENOTDIR に対応)
 ┃┣ PermissionErrorアクセス権がないユーザーで操作を行った場合。
(errno (システムシンボル) EACCES, EPERM に対応)
 ┃┣ ProcessLookupErrorプロセスが存在しない場合。
(errno (システムシンボル) ESRCH に対応)
 ┃┗ TimeoutErrorシステム関数がシステムレベルでタイムアウトした場合。
(errno (システムシンボル) ETIMEDOUT に対応)
 ┣ ReferenceError弱参照プロキシ(weakref.proxy()で生成)を使って、ガーベジコレクションにより回収した後の対象オブジェクトにアクセスした場合。
 ┣ RuntimeError他に分類できないエラーが検出された場合。
(以下、NotImplementedError, RecursionErrorの基底クラス。)
 ┃┣ NotImplementedErrorユーザ定義の基底クラスにおいて、抽象メソッドが派生クラスでオーバライドされていない場合。
(または クラスの一部が未実装である場合 等)
 ┃┗ RecursionError最大再帰回数 (sys.getrecursionlimit()) を超えた場合。
 ┣ SyntaxError構文エラーが発生した場合。
(以下、IndentationErrorの基底クラス。)
 ┃┗ IndentationErrorインデントに関する構文エラーが発生した場合。
(以下、TabErrorの基底クラス。)
 ┃  ┗ TabErrorインデントで使用するタブとスペースに一貫性がない場合。
 ┣ SystemErrorシステムエラー(インタプリタが検知した内部エラー)が発生した場合。
 ┣ TypeError型が不整合である場合。
 ┣ ValueError型は適切だが設定元(代入や引数等)の値が適切でない場合。
(以下、UnicodeErrorの基底クラス。)
 ┃┗ UnicodeErrorUnicodeのエンコード または デコードエラーが発生した場合。
(以下、UnicodeDecodeError, UnicodeEncodeError, UnicodeTranslateErrorの基底クラス。)
 ┃  ┣ UnicodeDecodeErrorUnicodeに関するエラーがデコード中に発生した場合。
 ┃  ┣ UnicodeEncodeErrorUnicodeに関するエラーがエンコード中に発生した場合。
 ┃  ┗ UnicodeTranslateErrorUnicodeに関するエラーが変換中に発生した場合。
 ┣ Warning下記サブクラスの警告が発生した場合。
(以下、DeprecationWarning ~ ResourceWarningの基底クラス。)
 ┣ DeprecationWarning廃止された機能に対する警告が発生した場合。
 ┣ PendingDeprecationWarning将来廃止される予定である機能に対する警告が発生した場合。
 ┣ RuntimeWarning曖昧なランタイム挙動に対する警告が発生した場合。
 ┣ SyntaxWarning曖昧な構文に対する警告が発生した場合。
 ┣ UserWarningユーザコードによって生成される警告が発生した場合。
 ┣ FutureWarning構文内に今後(次期バージョン等で)、意味やその構成が変わる予定があるものが含まれる場合。
 ┣ ImportWarningモジュールインポートの誤りが疑われる警告が発生した場合。
 ┣ UnicodeWarningUnicode関連の警告が発生した場合。
 ┣ BytesWarningbytes や bytearray に関連した警告が発生した場合。
 ┗ ResourceWarningリソースの使用に関連した警告が発生した場合。

※ 各項目の詳細は下記マニュアルを参照。

4. 組込み例外クラスのツリー表示サンプル


以下、前項の組込み例外クラス一覧をツリー表示した実装サンプル。
classtree 関数にBaseException を渡し、再帰的に BaseException を出力している。
 

  ▼ ツリー表示サンプル

$ python
 >>>
 >>> def classtree(cls, depth=0):
 ...     if depth == 0:
 ...         prefix = ''
 ...     else:
 ...         prefix = '.' * (depth * 3) + ' '
 ...     if cls.__name__.lower() == 'error':
 ...         print('{0}{1} ({2})'.format(prefix, cls.__name__, cls))
 ...     else:
 ...         print('{0}{1}'.format(prefix, cls.__name__))
 ...     for subcls in sorted(cls.__subclasses__(), key=lambda c: c.__name__):
 ...         classtree(subcls, depth+1)
 ...
 >>>
 >>> if __name__ == '__main__':
 ...     print('Python Version: {0}'.format(platform.python_version()))
 ...     print()
 ...     classtree(BaseException)
 ...
 
▼ 上記の実行結果

 Python Version: 3.6.4

 BaseException
 ... Exception
 ...... ArithmeticError
 ......... FloatingPointError
 ......... OverflowError
 ......... ZeroDivisionError
 ...... AssertionError
 ...... AttributeError
 ...... BufferError
 ...... EOFError
 ...... Error ()
 ...... ImportError
 ......... ModuleNotFoundError
 ......... ZipImportError
 ...... LookupError
 ......... CodecRegistryError
 ......... IndexError
 ......... KeyError
 ...... MemoryError
 ...... NameError
 ......... UnboundLocalError
 ...... OSError
 ......... BlockingIOError
 ......... ChildProcessError
 ......... ConnectionError
 ............ BrokenPipeError
 ............ ConnectionAbortedError
 ............ ConnectionRefusedError
 ............ ConnectionResetError
 ......... FileExistsError
 ......... FileNotFoundError
 ......... InterruptedError
 ......... IsADirectoryError
 ......... ItimerError
 ......... NotADirectoryError
 ......... PermissionError
 ......... ProcessLookupError
 ......... TimeoutError
 ......... UnsupportedOperation
 ...... ReferenceError
 ...... RuntimeError
 ......... BrokenBarrierError
 ......... NotImplementedError
 ......... RecursionError
 ......... _DeadlockError
 ...... StopAsyncIteration
 ...... StopIteration
 ...... StopTokenizing
 ...... SubprocessError
 ......... CalledProcessError
 ......... TimeoutExpired
 ...... SyntaxError
 ......... IndentationError
 ............ TabError
 ...... SystemError
 ......... CodecRegistryError
 ...... TokenError
 ...... TypeError
 ...... ValueError
 ......... UnicodeError
 ............ UnicodeDecodeError
 ............ UnicodeEncodeError
 ............ UnicodeTranslateError
 ......... UnsupportedOperation
 ...... Verbose
 ...... Warning
 ......... BytesWarning
 ......... DeprecationWarning
 ......... FutureWarning
 ......... ImportWarning
 ......... PendingDeprecationWarning
 ......... ResourceWarning
 ......... RuntimeWarning
 ......... SyntaxWarning
 ......... UnicodeWarning
 ......... UserWarning
 ...... _OptionError
 ...... error (<class 'sre_constants.error'>)
 ... GeneratorExit
 ... KeyboardInterrupt
 ... SystemExit

※ エラー:sre_constants.error は、正規表現が曖昧な場合に発生するようだが深くは触れない。
詳しくは、下記を参考。
what is sre_constants.error: nothing to repeat

また、help(__builtins__) からも例外クラスを確認できる。

$ python
 >>>
 >>> help(__builtins__)

 Help on built-in module builtins:
 
 NAME
     builtins - Built-in functions, exceptions, and other objects.
 
 DESCRIPTION
     Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.
 
 CLASSES
     object
         BaseException
             Exception
                 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
                 StopAsyncIteration
                 StopIteration
                 SyntaxError
                     IndentationError
                         TabError
                 SystemError
                 TypeError
                 ValueError
                     UnicodeError
                         UnicodeDecodeError
                         UnicodeEncodeError
                         UnicodeTranslateError
                 Warning
                     BytesWarning
                     DeprecationWarning
                     FutureWarning
                     ImportWarning
                     PendingDeprecationWarning
                     ProcessLookupError
                     TimeoutError
                 ReferenceError
                 RuntimeError
                     NotImplementedError
                     RecursionError
                 StopAsyncIteration
                 StopIteration
                 SyntaxError
                     IndentationError
                         TabError
                 SystemError
                 TypeError
                 ValueError
                     UnicodeError
                         UnicodeDecodeError
                         UnicodeEncodeError
                         UnicodeTranslateError
                 Warning
                     BytesWarning
                     DeprecationWarning
                     FutureWarning
                     ImportWarning
                     PendingDeprecationWarning
                     ResourceWarning
                     RuntimeWarning
                     SyntaxWarning
                     ResourceWarning
                     RuntimeWarning
                     SyntaxWarning
                     UnicodeWarning
                     UserWarning
             GeneratorExit
             KeyboardInterrupt
             SystemExit
             … (以降省略)

以上。



【参考文献】
金城 俊哉 (2018) 『現場ですぐに使える! Pythonプログラミング逆引き大全313の極意』株式会社昭和システム


Copyright UNISIA-SE All Rights Reserved.
s-hama@unisia-se.jp