組み蟌み䟋倖¶

Python においお、すべおの䟋倖は BaseException から掟生したクラスのむンスタンスでなければなりたせん。特定のクラスを蚀及する except 節を䌎う try 文においお、その節はそのクラスから掟生した䟋倖クラスも凊理したすが、そのクラスの掟生 元 の䟋倖クラスは凊理したせん。サブクラス化の関係にない 2 ぀の䟋倖クラスは、それらが同じ名前だった堎合でも等しくなりえたせん。

この章で挙げる組み蟌み䟋倖は、むンタプリタや組み蟌み関数によっお生成されたす。特に泚蚘しないかぎり、これらぱラヌの詳しい原因を瀺す "関連倀 (associated value)" を持ちたす。この倀は、耇数の情報 (゚ラヌコヌドや、そのコヌドを説明する文字列など) の文字列かタプルです。関連倀は通垞、䟋倖クラスのコンストラクタに匕数ずしお枡されたす。

ナヌザによるコヌドも組み蟌み䟋倖を送出できたす。これを䜿っお、䟋倖ハンドラをテストしたり、むンタプリタが同じ䟋倖を送出する状況ず "ちょうど同じような" ゚ラヌ条件であるこずを報告したりできたす。しかし、ナヌザのコヌドが適切でない゚ラヌを送出するのを劚げる方法はないので泚意しおください。

組み蟌み䟋倖クラスは新たな䟋倖を定矩するためにサブクラス化するこずができたす。新しい䟋倖は、Exception クラスかそのサブクラスの䞀぀から掟生するこずをお勧めしたす。 BaseException からは掟生しないで䞋さい。䟋倖を定矩する䞊での詳しい情報は、 Python チュヌトリアルの ナヌザヌ定矩䟋倖 の項目にありたす。

䟋倖コンテキスト¶

䟋倖オブゞェクトの3぀の属性は、䟋倖が送出された垞甚に関する情報を提䟛したす:

BaseException.__context__¶
BaseException.__cause__¶
BaseException.__suppress_context__¶

When raising a new exception while another exception is already being handled, the new exception's __context__ attribute is automatically set to the handled exception. An exception may be handled when an except or finally clause, or a with statement, is used.

This implicit exception context can be supplemented with an explicit cause by using from with raise:

raise new_exc from original_exc

from に続く匏は䟋倖か None でなくおはなりたせん。 匏は送出される䟋倖の __cause__ ずしお蚭定されたす。 __cause__ を蚭定するこずは、 __suppress_context__ 属性を暗黙的に True に蚭定するこずにもなるので、 raise new_exc from None を䜿うこずで効率的に叀い䟋倖を新しいもので眮き換えお衚瀺する (䟋えば、 KeyError を AttributeError に眮き換え)、叀い䟋倖はデバッグ時の調査で䜿えるよう __context__ に残すこずができたす。

デフォルトの traceback 衚瀺コヌドは、䟋倖自䜓の traceback に加え、これらの連鎖された䟋倖を衚瀺したす。__cause__ で明瀺的に連鎖させた䟋倖は、存圚するならば垞に衚瀺されたす。__context__ で暗黙に連鎖させた䟋倖は、__cause__ が None か぀ __suppress_context__ が false の堎合にのみ衚瀺されたす。

いずれにせよ、連鎖された䟋倖に続いお、その䟋倖自䜓は垞に衚瀺されたす。そのため、traceback の最終行には、垞に送出された最埌の䟋倖が衚瀺されたす。

組み蟌み䟋倖から継承する¶

User code can create subclasses that inherit from an exception type. It's recommended to only subclass one exception type at a time to avoid any possible conflicts between how the bases handle the args attribute, as well as due to possible memory layout incompatibilities.

CPython 実装の詳现: Most built-in exceptions are implemented in C for efficiency, see: Objects/exceptions.c. Some have custom memory layouts which makes it impossible to create a subclass that inherits from multiple exception types. The memory layout of a type is an implementation detail and might change between Python versions, leading to new conflicts in the future. Therefore, it's recommended to avoid subclassing multiple exception types altogether.

基底クラス¶

以䞋の䟋倖は、䞻に他の䟋倖の基底クラスずしお䜿われたす。

exception BaseException¶

党おの組み蟌み䟋倖の基底クラスです。ナヌザ定矩の䟋倖に盎接継承されるこずは意図されおいたせん (継承には Exception を䜿っおください)。このクラスのむンスタンスに str() が呌ばれた堎合、むンスタンスぞの匕数の衚珟か、匕数が無い堎合には空文字列が返されたす。

args¶

䟋倖コンストラクタに䞎えられた匕数のタプルです。組み蟌み䟋倖は普通、゚ラヌメッセヌゞを䞎える䞀぀の文字列だけを匕数ずしお呌ばれたすが、䞭には (OSError など) いく぀かの匕数を必芁ずし、このタプルの芁玠に特別な意味を蟌めるものもありたす。

with_traceback(tb)¶

This method sets tb as the new traceback for the exception and returns the exception object. It was more commonly used before the exception chaining features of PEP 3134 became available. The following example shows how we can convert an instance of SomeException into an instance of OtherException while preserving the traceback. Once raised, the current frame is pushed onto the traceback of the OtherException, as would have happened to the traceback of the original SomeException had we allowed it to propagate to the caller.

try:
    ...
except SomeException:
    tb = sys.exception().__traceback__
    raise OtherException(...).with_traceback(tb)
__traceback__¶

A writable field that holds the traceback object associated with this exception. See also: raise 文.

add_note(note)¶

䟋倖のノヌトずしお文字列 note を远加したす。ノヌトは暙準のトレヌスバックで䟋倖文字列の埌に衚瀺されたす。note が文字列以倖の堎合 TypeError が送出されたす。

Added in version 3.11.

__notes__¶

add_note() で远加された䟋倖のノヌトのリスト。この属性は add_note() を呌び出すず生成されたす。

Added in version 3.11.

exception Exception¶

システム終了以倖の党おの組み蟌み䟋倖はこのクラスから掟生しおいたす。党おのナヌザ定矩䟋倖もこのクラスから掟生させるべきです。

exception ArithmeticError¶

算術䞊の様々な゚ラヌに察しお送出される組み蟌み䟋倖 OverflowError, ZeroDivisionError, FloatingPointError の基底クラスです。

exception BufferError¶

バッファ に関連する操䜜が行えなかったずきに送出されたす。

exception LookupError¶

マッピングたたはシヌケンスで䜿われたキヌやむンデクスが無効な堎合に送出される䟋倖 IndexError および KeyError の基底クラスです。 codecs.lookup() によっお盎接送出されるこずもありたす。

具象䟋倖¶

以䞋の䟋倖は、通垞送出される䟋倖です。

exception AssertionError¶

assert 文が倱敗した堎合に送出されたす。

exception AttributeError¶

属性参照 (属性参照 を参照) や代入が倱敗した堎合に送出されたす (オブゞェクトが属性の参照や属性の代入をたったくサポヌトしおいない堎合には TypeError が送出されたす)。

The optional name and obj keyword-only arguments set the corresponding attributes:

name¶

The name of the attribute that was attempted to be accessed.

obj¶

The object that was accessed for the named attribute.

バヌゞョン 3.10 で倉曎: name および obj 属性が远加されたした。

exception EOFError¶

Raised when the input() function hits an end-of-file condition (EOF) without reading any data. (Note: the io.TextIOBase.read() and io.IOBase.readline() methods return an empty string when they hit EOF.)

exception FloatingPointError¶

珟圚は䜿われおいたせん。

exception GeneratorExit¶

ゞェネレヌタ や コルヌチン が閉じられたずきに送出されたす。 generator.close() ず coroutine.close() を参照しおください。この䟋倖は厳密に蚀えば゚ラヌではないので、 Exception ではなく BaseException を盎接継承しおいたす。

exception ImportError¶

import 文でモゞュヌルをロヌドしようずしお問題が発生するず送出されたす。 from ... import の䞭の"from list" (蚳泚... の郚分)の名前が芋぀からないずきにも送出されたす。

オブションのキヌワヌド専甚匕数 name ず path は、察応する属性に蚭定されたす:

name¶

むンポヌトを詊みたモゞュヌルの名前。

path¶

䟋倖を匕き起こしたファむルのパス。

バヌゞョン 3.3 で倉曎: name および path 属性が远加されたした。

exception ModuleNotFoundError¶

ImportError のサブクラスで、import 文でモゞュヌルが芋぀からない堎合に送出されたす。たた、 sys.modules に None が含たれる堎合にも送出されたす。

Added in version 3.6.

exception IndexError¶

シヌケンスの添字が範囲倖の堎合に送出されたす。 (スラむスのむンデクスはシヌケンスの範囲に収たるように暗黙のうちに調敎されたす; むンデクスが敎数でない堎合、 TypeError が送出されたす。)

exception KeyError¶

マッピング (蟞曞) のキヌが、既存のキヌの集合内に芋぀からなかった堎合に送出されたす。

exception KeyboardInterrupt¶

ナヌザが割り蟌みキヌ (通垞は Control-C たたは Delete) を抌した堎合に送出されたす。実行䞭、割り蟌みは定期的に監芖されたす。Exception を捕捉するコヌドに誀っお捕捉されおむンタプリタの終了が阻害されないように、この䟋倖は BaseException を継承しおいたす。

泚釈

Catching a KeyboardInterrupt requires special consideration. Because it can be raised at unpredictable points, it may, in some circumstances, leave the running program in an inconsistent state. It is generally best to allow KeyboardInterrupt to end the program as quickly as possible or avoid raising it entirely. (See Note on Signal Handlers and Exceptions.)

exception MemoryError¶

ある操䜜䞭にメモリが䞍足したが、その状況は (オブゞェクトをいく぀か消去するこずで) ただ埩旧可胜かもしれない堎合に送出されたす。この䟋倖の関連倀は、メモリ䞍足になった (内郚) 操䜜の皮類を瀺す文字列です。䞋局のメモリ管理アヌキテクチャ (C の malloc() 関数) のために、むンタプリタが珟状から完璧に埩旧できるずはかぎらないので泚意しおください。それでも、プログラムの暎走が原因の堎合に備えお実行スタックのトレヌスバックを出力できるように、䟋倖が送出されたす。

exception NameError¶

ロヌカルたたはグロヌバルの名前が芋぀からなかった堎合に送出されたす。これは非修食の (蚳泚: spam.egg ではなく単に egg のような) 名前のみに適甚されたす。関連倀は芋぀からなかった名前を含む゚ラヌメッセヌゞです。

The optional name keyword-only argument sets the attribute:

name¶

The name of the variable that was attempted to be accessed.

バヌゞョン 3.10 で倉曎: name 属性が远加されたした。

exception NotImplementedError¶

この䟋倖は RuntimeError から掟生しおいたす。ナヌザ定矩の基底クラスにおいお、抜象メ゜ッドが掟生クラスでオヌバラむドされるこずを芁求する堎合にこの䟋倖を送出しなくおはなりたせん。たたはクラスは実装䞭であり本来の実装を远加する必芁があるこずを瀺したす。

泚釈

挔算子やメ゜ッドがサポヌトされおいないこずを瀺す目的でこの䟋倖を䜿甚するべきではありたせん。そのようなケヌスではオペレヌタやメ゜ッドを未定矩のたたずするか、サブクラスの堎合は None を蚭定しおください。

泚意

NotImplementedError and NotImplemented are not interchangeable. This exception should only be used as described above; see NotImplemented for details on correct usage of the built-in constant.

exception OSError([arg])¶
exception OSError(errno, strerror[, filename[, winerror[, filename2]]])

この䟋倖はシステム関数がシステム関連の゚ラヌを返した堎合に送出されたす。䟋えば "file not found" や "disk full" のような I/O の倱敗が発生したずきです (匕数の型が䞍正な堎合や、他の偶発的な゚ラヌは陀きたす)。

コンストラクタの2番目の圢匏は䞋蚘の察応する属性を蚭定したす。指定されなかった堎合属性はデフォルトで None です。埌方互換性のために、匕数が3぀枡された堎合、args 属性は最初の2぀の芁玠のみからなるタプルを持ちたす。

コンストラクタは実際には、 OS exceptions で述べられおいる OSError のサブクラスを返すこずがよくありたす。特定のサブクラスは最終的な errno 倀によりたす。この挙動は OSError を盎接たたぱむリアスで構築し、サブクラス化時に継承されなかった堎合にのみ発生したす。

errno¶

C 倉数 errno に由来する数倀゚ラヌコヌドです。

winerror¶

Windows においお、ネむティブ Windows ゚ラヌコヌドを䞎えたす。そしお errno 属性は POSIX でいうネむティブ゚ラヌコヌドぞのおよその翻蚳です。

Windows では、winerror コンストラクタ匕数が敎数の堎合 errno 属性は Windows ゚ラヌコヌドから決定され、errno 匕数は無芖されたす。他のプラットフォヌムでは winerror 匕数は無芖され、 winerror 属性は存圚したせん。

strerror¶

The corresponding error message, as provided by the operating system. It is formatted by the C functions perror() under POSIX, and FormatMessage() under Windows.

filename¶
filename2¶

ファむルシステムパスが1぀関䞎する䟋倖 (䟋えば open() や os.unlink()) の堎合、filename は関数に枡されたファむル名です。 ファむルシステムパスが2぀関䞎する関数 (䟋えば os.rename()) の堎合、filename2 は関数に枡された2぀目のファむル名です。

バヌゞョン 3.3 で倉曎: EnvironmentError, IOError, WindowsError, socket.error, select.error and mmap.error have been merged into OSError, and the constructor may return a subclass.

バヌゞョン 3.4 で倉曎: filename 属性が filesystem encoding and error handler の゚ンコヌディングで゚ンコヌドやデコヌドされた名前から、関数に枡された元々のファむル名になりたした。 たた、filename2 コンストラクタ匕数が远加されたした。

exception OverflowError¶

算術挔算の結果が衚珟できない倧きな倀になった堎合に送出されたす。これは敎数では起こりたせん (むしろ MemoryError が送出されるこずになるでしょう)。しかし、歎史的な理由のため、芁求された範囲の倖の敎数に察しお OverflowError が送出されるこずがありたす。C の浮動小数点挔算の䟋倖凊理は暙準化されおいないので、ほずんどの浮動小数点挔算もチェックされたせん。

exception PythonFinalizationError¶

This exception is derived from RuntimeError. It is raised when an operation is blocked during interpreter shutdown also known as Python finalization.

Examples of operations which can be blocked with a PythonFinalizationError during the Python finalization:

sys.is_finalizing() 関数も参照しおください。

Added in version 3.13: 以前は RuntimeError をそのたた送出しおいたした。

バヌゞョン 3.14 で倉曎: threading.Thread.join() can now raise this exception.

exception RecursionError¶

この䟋倖は RuntimeError を継承しおいたす。むンタヌプリタが最倧再垰深床 (sys.getrecursionlimit() を参照) の超過を怜出するず送出されたす。

Added in version 3.5: 以前は RuntimeError をそのたた送出しおいたした。

exception ReferenceError¶

weakref.proxy() によっお生成された匱参照 (weak reference) プロキシを䜿っお、ガヌベゞコレクションによっお回収された埌の参照察象オブゞェクトの属性にアクセスした堎合に送出されたす。匱参照に぀いおは weakref モゞュヌルを参照しおください。

exception RuntimeError¶

他のカテゎリに分類できない゚ラヌが怜出された堎合に送出されたす。関連倀は、䜕が問題だったのかをより詳现に瀺す文字列です。

exception StopIteration¶

組蟌み関数 next() ず iterator の __next__() メ゜ッドによっお、そのむテレヌタが生成するアむテムがこれ以䞊ないこずを䌝えるために送出されたす。

value¶

この䟋倖オブゞェクトには䞀぀の属性 value があり、䟋倖を構成する際に匕数ずしお䞎えられ、デフォルトは None です。

generator や coroutine 関数が返るずき、新しい StopIteration むンスタンスが送出されたす。 関数の返り倀は䟋倖のコンストラクタの value 匕数ずしお䜿われたす。

ゞェネレヌタのコヌドが盎接的あるいは間接的に StopIteration を送出する堎合は、 RuntimeError に倉換されたす (StopIteration は倉換埌の䟋倖の原因ずしお保持されたす)。

バヌゞョン 3.3 で倉曎: value 属性ずゞェネレヌタ関数が倀を返すためにそれを䜿う機胜が远加されたした。

バヌゞョン 3.5 で倉曎: from __future__ import generator_stop による RuntimeError ぞの倉換が導入されたした。 PEP 479 を参照しおください。

バヌゞョン 3.7 で倉曎: PEP 479 が党おのコヌドでデフォルトで有効化されたした: ゞェネレヌタから送出された StopIteration は RuntimeError に倉換されたす。

exception StopAsyncIteration¶

むテレヌションを停止するために、 asynchronous iterator オブゞェクトの __anext__() メ゜ッドによっお返される必芁がありたす。

Added in version 3.5.

exception SyntaxError(message, details)¶

パヌザが構文゚ラヌに遭遇した堎合に送出されたす。この䟋倖は import 文、組み蟌み関数 compile()、exec() や eval() 、初期化スクリプトの読み蟌みや暙準入力で (察話的な実行時にも) 起こる可胜性がありたす。

䟋倖むンスタンスの str() ぱラヌメッセヌゞのみを返したす。詳现はタプルで、個々の属性ずしおも利甚できたす。

filename¶

構文゚ラヌが発生したファむルの名前。

lineno¶

ファむルの゚ラヌが発生した行番号。1から数えはじめるため、ファむルの最初の行の lineno は1です。

offset¶

行の゚ラヌが発生した列番号。1から数えはじめるため、行の最初の文字の offset は1です。

text¶

゚ラヌを含む゜ヌスコヌドのテキスト。

end_lineno¶

ファむルの゚ラヌが発生した最埌の行番号。1から数えはじめるため、ファむルの最初の行の lineno は1です。

end_offset¶

行の゚ラヌが発生した最埌の列番号。1から数えはじめるため、行の最初の文字の offset は1です。

For errors in f-string fields, the message is prefixed by "f-string: " and the offsets are offsets in a text constructed from the replacement expression. For example, compiling f'Bad {a b} field' results in this args attribute: ('f-string: ...', ('', 1, 2, '(a b)n', 1, 5)).

バヌゞョン 3.10 で倉曎: end_lineno および end_offset 属性が远加されたした。

exception IndentationError¶

正しくないむンデントに関する構文゚ラヌの基底クラスです。これは SyntaxError のサブクラスです。

exception TabError¶

タブずスペヌスを䞀貫しない方法でむンデントに䜿っおいるずきに送出されたす。これは IndentationError のサブクラスです。

exception SystemError¶

Raised when the interpreter finds an internal error, but the situation does not look so serious to cause it to abandon all hope. The associated value is a string indicating what went wrong (in low-level terms). In CPython, this could be raised by incorrectly using Python's C API, such as returning a NULL value without an exception set.

If you're confident that this exception wasn't your fault, or the fault of a package you're using, you should report this to the author or maintainer of your Python interpreter. Be sure to report the version of the Python interpreter (sys.version; it is also printed at the start of an interactive Python session), the exact error message (the exception's associated value) and if possible the source of the program that triggered the error.

exception SystemExit¶

This exception is raised by the sys.exit() function. It inherits from BaseException instead of Exception so that it is not accidentally caught by code that catches Exception. This allows the exception to properly propagate up and cause the interpreter to exit. When it is not handled, the Python interpreter exits; no stack traceback is printed. The constructor accepts the same optional argument passed to sys.exit(). If the value is an integer, it specifies the system exit status (passed to C's exit() function); if it is None, the exit status is zero; if it has another type (such as a string), the object's value is printed and the exit status is one.

sys.exit() は、クリヌンアップのための凊理 (try 文の finally 節) が実行されるようにするため、たたデバッガが制埡䞍胜になるリスクを冒さずにスクリプトを実行できるようにするために䟋倖に倉換されたす。即座に終了するこずが真に匷く必芁であるずき (䟋えば、os.fork() を呌んだ埌の子プロセス内) には os._exit() 関数を䜿うこずができたす。

code¶

コンストラクタに枡された終了ステヌタス又ぱラヌメッセヌゞ。(デフォルトは None)

exception TypeError¶

組み蟌み挔算たたは関数が適切でない型のオブゞェクトに察しお適甚された際に送出されたす。関連倀は型の䞍敎合に関しお詳现を述べた文字列です。

この䟋倖は、そのオブゞェクトで実行しようずした操䜜がサポヌトされおおらず、その予定もない堎合にナヌザヌコヌドから送出されるかもしれたせん。オブゞェクトでその操䜜をサポヌトする぀もりだが、ただ実装を提䟛しおいないのであれば、送出する適切な䟋倖は NotImplementedError です。

誀った型の匕数が枡された堎合は (䟋えば、int が期埅されるのに、list が枡された) TypeError ずなるべきです。しかし、誀った倀(䟋えば、期埅する範囲倖の数)が匕数ずしお枡された堎合は、 ValueError ずなるべきです。

exception UnboundLocalError¶

関数やメ゜ッド内のロヌカルな倉数に察しお参照を行ったが、その倉数には倀が代入されおいなかった堎合に送出されたす。 NameError のサブクラスです。

exception UnicodeError¶

Unicode に関する゚ンコヌドたたはデコヌドの゚ラヌが発生した際に送出されたす。 ValueError のサブクラスです。

UnicodeError ぱンコヌドたたはデコヌドの゚ラヌの説明を属性ずしお持っおいたす。䟋えば、 err.object[err.start:err.end] は、無効な入力のうちコヌデックが凊理に倱敗した箇所を衚したす。

encoding¶

゚ラヌを送出した゚ンコヌディングの名前です。

reason¶

そのコヌデック゚ラヌを説明する文字列です。

object¶

コヌデックが゚ンコヌドたたはデコヌドしようずしたオブゞェクトです。

start¶

object の最初の無効なデヌタのむンデクスです。

This value should not be negative as it is interpreted as an absolute offset but this constraint is not enforced at runtime.

end¶

object の最埌の無効なデヌタの次のむンデクスです。

This value should not be negative as it is interpreted as an absolute offset but this constraint is not enforced at runtime.

exception UnicodeEncodeError¶

Unicode 関連の゚ラヌが゚ンコヌド䞭に発生した際に送出されたす。 UnicodeError のサブクラスです。

exception UnicodeDecodeError¶

Unicode 関連の゚ラヌがデコヌド䞭に発生した際に送出されたす。 UnicodeError のサブクラスです。

exception UnicodeTranslateError¶

Unicode 関連の゚ラヌが倉換䞭に発生した際に送出されたす。 UnicodeError のサブクラスです。

exception ValueError¶

挔算子や関数が、正しい型だが適切でない倀を持぀匕数を受け取ったずきや、 IndexError のようなより詳现な䟋倖では蚘述できない状況で送出されたす。

exception ZeroDivisionError¶

陀算や剰䜙挔算の第二匕数が 0 であった堎合に送出されたす。関連倀は文字列で、その挔算における被挔算子ず挔算子の型を瀺したす。

以䞋の䟋倖は、過去のバヌゞョンずの埌方互換性のために残されおいたす; Python 3.3 より、これらは OSError の゚むリアスです。

exception EnvironmentError¶
exception IOError¶
exception WindowsError¶

Windows でのみ利甚できたす。

OS 䟋倖¶

以䞋の䟋倖は OSError のサブクラスで、システム゚ラヌコヌドに䟝存しお送出されたす。

exception BlockingIOError¶

ある操䜜が、ノンブロッキング操䜜に蚭定されたオブゞェクト (䟋えば゜ケット) をブロックしそうになった堎合に送出されたす。errno EAGAIN, EALREADY, EWOULDBLOCK および EINPROGRESS に察応したす。

BlockingIOError は、 OSError の属性に加えお䞀぀の属性を持ちたす:

characters_written¶

An integer containing the number of bytes written to the stream before it blocked. This attribute is available when using the buffered I/O classes from the io module.

exception ChildProcessError¶

子プロセスの操䜜が倱敗した堎合に送出されたす。errno ECHILD に察応したす。

exception ConnectionError¶

コネクション関係の問題の基底クラス。

サブクラスは BrokenPipeError, ConnectionAbortedError, ConnectionRefusedError, ConnectionResetError です。

exception BrokenPipeError¶

ConnectionError のサブクラスで、もう䞀方の端が閉じられたパむプに曞き蟌こもうずするか、曞き蟌みのためにシャットダりンされた゜ケットに曞き蟌こもうずした堎合に発生したす。 errno EPIPE ず ESHUTDOWN に察応したす。

exception ConnectionAbortedError¶

ConnectionError のサブクラスで、接続の詊行が通信盞手によっお䞭断された堎合に発生したす。 errno ECONNABORTED に察応したす。

exception ConnectionRefusedError¶

ConnectionError のサブクラスで、接続の詊行が通信盞手によっお拒吊された堎合に発生したす。 errno ECONNREFUSED に察応したす。

exception ConnectionResetError¶

ConnectionError のサブクラスで、接続が通信盞手によっおリセットされた堎合に発生したす。 errno ECONNRESET に察応したす。

exception FileExistsError¶

すでに存圚するファむルやディレクトリを䜜成しようずした堎合に送出されたす。errno EEXIST に察応したす。

exception FileNotFoundError¶

芁求されたファむルやディレクトリが存圚しない堎合に送出されたす。errno ENOENT に察応したす。

exception InterruptedError¶

システムコヌルが入力信号によっお䞭断された堎合に送出されたす。errno EINTR に察応したす。

バヌゞョン 3.5 で倉曎: シグナルハンドラが䟋倖を送出せず、システムコヌルが信号で䞭断された堎合 Python は InterruptedError を送出する代わりにシステムコヌルを再詊行するようになりたした (論拠に぀いおは PEP 475 を参照しおください) 。

exception IsADirectoryError¶

ディレクトリに (os.remove() などの) ファむル操䜜が芁求された堎合に送出されたす。errno EISDIR に察応したす。

exception NotADirectoryError¶

ディレクトリぞの操䜜(たずえば os.listdir())をディレクトリ以倖に察しお芁求された堎合に送出されたす。倚くのPOSIXプラットフォヌムではディレクトリではないファむルをディレクトリずしお開いたり移動するずきにも発生する堎合がありたす。errno ENOTDIR に察応したす。

exception PermissionError¶

十分なアクセス暩、䟋えばファむルシステム暩限のない操䜜が詊みられた堎合に送出されたす。errno EACCES、EPERM および ENOTCAPABLE に察応したす。

バヌゞョン 3.11.1 で倉曎: WASIの ENOTCAPABLE は PermissionError にマップされたした。

exception ProcessLookupError¶

䞎えられたプロセスが存圚しない堎合に送出されたす。errno ESRCH に察応したす。

exception TimeoutError¶

システム関数がシステムレベルでタむムアりトした堎合に送出されたす。errno ETIMEDOUT に察応したす。

Added in version 3.3: 䞊蚘のすべおの OSError サブクラスが远加されたした。

参考

PEP 3151 - OS および IO 䟋倖階局の手盎し

譊告¶

次の䟋倖は譊告カテゎリずしお䜿われたす。詳现に぀いおは 譊告カテゎリ のドキュメントを参照しおください。

exception Warning¶

譊告カテゎリの基底クラスです。

exception UserWarning¶

ナヌザコヌドによっお生成される譊告の基底クラスです。

exception DeprecationWarning¶

他の Python 開発者ぞ向けお譊告を発するずきの、廃止予定の機胜に぀いおの譊告の基底クラスです。

__main__ モゞュヌルを陀いお(PEP 565)、デフォルトの譊告フィルタヌで無効化されおいたす。Python Development Mode を有効にするずこの譊告が衚瀺されたす。

The deprecation policy is described in PEP 387.

exception PendingDeprecationWarning¶

叀くなっお将来的に廃止される予定だが、今のずころは廃止されおいない機胜に぀いおの譊告の基底クラスです。

近々起こる可胜性のある機胜廃止に぀いお譊告を発するこずはたれなので、このクラスはめったに䜿われず、既に決たっおいる廃止に぀いおは DeprecationWarning が望たしいです。

デフォルトの譊告フィルタヌで無効化されおいたす。Python Development Mode を有効にするずこの譊告が衚瀺されたす。

The deprecation policy is described in PEP 387.

exception SyntaxWarning¶

曖昧な構文に察する譊告の基底クラスです。

This warning is typically emitted when compiling Python source code, and usually won't be reported when running already compiled code.

exception RuntimeWarning¶

あいたいなランタむム挙動に察する譊告の基底クラスです。

exception FutureWarning¶

Python で曞かれたアプリケヌションの゚ンドナヌザヌぞ向けお譊告を発するずきの、廃止予定の機胜に぀いおの譊告の基底クラスです。

exception ImportWarning¶

モゞュヌルむンポヌトの誀りず思われるものに察する譊告の基底クラスです。

デフォルトの譊告フィルタヌで無効化されおいたす。Python Development Mode を有効にするずこの譊告が衚瀺されたす。

exception UnicodeWarning¶

Unicode に関連した譊告の基底クラスです。

exception EncodingWarning¶

゚ンコヌディングに関連した譊告の基底クラスです。

詳现は Opt-in EncodingWarning を参照しおください。

Added in version 3.10.

exception BytesWarning¶

bytes や bytearray に関連した譊告の基底クラスです。

exception ResourceWarning¶

リ゜ヌスの䜿甚に関連した譊告の基底クラスです。

デフォルトの譊告フィルタヌで無効化されおいたす。Python Development Mode を有効にするずこの譊告が衚瀺されたす。

Added in version 3.2.

䟋倖グルヌプ¶

以䞋は関係がない耇数の䟋倖を送出する必芁があるずきに䜿甚したす。䟋倖グルヌプは䟋倖の階局構造の䞀郚のため、他の䟋倖ず同様 except で凊理できたす。たた、except* によっお刀別でき、䟋倖グルヌプに含たれおいる䟋倖の型に基づいおサブグルヌプにマッチしたす。

exception ExceptionGroup(msg, excs)¶
exception BaseExceptionGroup(msg, excs)¶

この2぀の䟋倖型は䞀連の䟋倖 excs を包含したす。msg 匕数は文字列の必芁がありたす。2぀のクラスの異なる点は、BaseException は BaseExceptionGroup を拡匵しお任意の䟋倖を含められたすが、ExceptionGroup は Exception を拡匵しお Exception のサブクラスのみを含められたす。この蚭蚈により except Exception は ExceptionGroup をキャッチしたすが、BaseExceptionGroup はキャッチしたせん。

BaseExceptionGroup のコンストラクタヌは含たれる䟋倖がすべお Exception の堎合は BaseExceptionGroup ではなく ExceptionGroup を返すように自動的に遞択されたす。䞀方 ExceptionGroup コンストラクタは、Exception サブクラス以倖の䟋倖を含む堎合は TypeError を送出したす。

Exception groups are generic over the type of their contained exceptions.

CPython 実装の詳现: The excs parameter may be any sequence, but lists and tuples are specifically processed more efficiently here. For optimal performance, pass a tuple as excs.

message¶

コンストラクタの msg 匕数。この属性は読み蟌み専甚です。

exceptions¶

コンストラクタに枡された䞀連の excs に含たれる䟋倖のタプルです。この属性は読み蟌み専甚です。

subgroup(condition)¶

珟圚のグルヌプで 条件 にマッチする瀌儀のみを含む䟋倖グルヌプを返したす。結果が空の堎合は None を返したす。

The condition can be an exception type or tuple of exception types, in which case each exception is checked for a match using the same check that is used in an except clause. The condition can also be a callable (other than a type object) that accepts an exception as its single argument and returns true for the exceptions that should be in the subgroup.

The nesting structure of the current exception is preserved in the result, as are the values of its message, __traceback__, __cause__, __context__ and __notes__ fields. Empty nested groups are omitted from the result.

The condition is checked for all exceptions in the nested exception group, including the top-level and any nested exception groups. If the condition is true for such an exception group, it is included in the result in full.

Added in version 3.13: condition can be any callable which is not a type object.

split(condition)¶

subgroup() ず䌌おたすが (match, rest) のペアを返したす。match は subgroup(condition) で rest は残りのマッチしない郚分です。

derive(excs)¶

同じ message の䟋倖グルヌプを返したすが、excs の䟋倖を含んでいたす。

This method is used by subgroup() and split(), which are used in various contexts to break up an exception group. A subclass needs to override it in order to make subgroup() and split() return instances of the subclass rather than ExceptionGroup.

subgroup() ず split() は __traceback__、__cause__、__context__ ず __notes__ フィヌルドを元の䟋倖グルヌプから derive() が返す䟋倖グルヌプにコピヌするため、derive() ではこれらのフィヌルドを曎新する必芁がありたせん。

>>> class MyGroup(ExceptionGroup):
...     def derive(self, excs):
...         return MyGroup(self.message, excs)
...
>>> e = MyGroup("eg", [ValueError(1), TypeError(2)])
>>> e.add_note("a note")
>>> e.__context__ = Exception("context")
>>> e.__cause__ = Exception("cause")
>>> try:
...    raise e
... except Exception as e:
...    exc = e
...
>>> match, rest = exc.split(ValueError)
>>> exc, exc.__context__, exc.__cause__, exc.__notes__
(MyGroup('eg', [ValueError(1), TypeError(2)]), Exception('context'), Exception('cause'), ['a note'])
>>> match, match.__context__, match.__cause__, match.__notes__
(MyGroup('eg', [ValueError(1)]), Exception('context'), Exception('cause'), ['a note'])
>>> rest, rest.__context__, rest.__cause__, rest.__notes__
(MyGroup('eg', [TypeError(2)]), Exception('context'), Exception('cause'), ['a note'])
>>> exc.__traceback__ is match.__traceback__ is rest.__traceback__
True

Note that BaseExceptionGroup defines __new__(), so subclasses that need a different constructor signature need to override that rather than __init__(). For example, the following defines an exception group subclass which accepts an exit_code and constructs the group's message from it.

class Errors(ExceptionGroup):
   def __new__(cls, errors, exit_code):
      self = super().__new__(Errors, f"exit code: {exit_code}", errors)
      self.exit_code = exit_code
      return self

   def derive(self, excs):
      return Errors(excs, self.exit_code)

Like ExceptionGroup, any subclass of BaseExceptionGroup which is also a subclass of Exception can only wrap instances of Exception.

Added in version 3.11.

䟋倖のクラス階局¶

組み蟌み䟋倖のクラス階局は以䞋のずおりです:

BaseException
 ├── BaseExceptionGroup
 ├── GeneratorExit
 ├── KeyboardInterrupt
 ├── SystemExit
 └── Exception
      ├── ArithmeticError
      │    ├── FloatingPointError
      │    ├── OverflowError
      │    └── ZeroDivisionError
      ├── AssertionError
      ├── AttributeError
      ├── BufferError
      ├── EOFError
      ├── ExceptionGroup [BaseExceptionGroup]
      ├── 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
      │    ├── PythonFinalizationError
      │    └── RecursionError
      ├── StopAsyncIteration
      ├── StopIteration
      ├── SyntaxError
      │    └── IndentationError
      │         └── TabError
      ├── SystemError
      ├── TypeError
      ├── ValueError
      │    └── UnicodeError
      │         ├── UnicodeDecodeError
      │         ├── UnicodeEncodeError
      │         └── UnicodeTranslateError
      └── Warning
           ├── BytesWarning
           ├── DeprecationWarning
           ├── EncodingWarning
           ├── FutureWarning
           ├── ImportWarning
           ├── PendingDeprecationWarning
           ├── ResourceWarning
           ├── RuntimeWarning
           ├── SyntaxWarning
           ├── UnicodeWarning
           └── UserWarning