內建的例外

在 Python 中,所有例外必須是從 BaseException 衍生的類別的實例。在陳述式 try 搭配 except 子句裡提到一個特定的類別時,那個子句也會處理任何從該類別衍生的例外類別(但不會處理該類別衍生自的例外類別)。兩個不是由子類別關係關聯起來的例外類別永遠不相等,就算它們有相同的名稱也是如此。

此章節裡列出的內建例外可以從直譯器或內建函式產生。除了特別提到的地方之外,它們會有一個關聯值表示錯誤發生的詳細原因。這可能是一個字串,或者是一些資訊項目組成的元組(例如一個錯誤代碼及一個解釋該代碼的字串)。這個關聯值通常當作引數傳遞給例外類別的建構函式。

使用者的程式碼可以引發內建例外。這可以用來測試例外處理器或者用來回報一個錯誤條件,就像直譯器會引發相同例外的情況;但需要注意的是沒有任何方式可以避免使用者的程式碼引發不適當的錯誤。

可以從內建的例外類別定義新的例外子類別;程式設計師被鼓勵從 Exception 類別或其子類別衍生新的例外,而不是從 BaseException 來衍生。更多關於定義例外的資訊可以在 Python 教學中的使用者自定的例外裡取得。

例外的情境

三個例外物件上的屬性提供關於引發此例外的情境的資訊:

BaseException.__context__
BaseException.__cause__
BaseException.__suppress_context__

當引發一個新的例外而同時有另一個例外已經正在被處理時,這個新例外的 __context__ 屬性會自動被設成那個已處理的例外。當使用 exceptfinally 子句或 with 陳述式的時候例外會被處理。

這個隱含的例外情境可以透過使用 from 搭配 raise 來補充明確的原因:

raise new_exc from original_exc

from 後面的運算式必須是一個例外或 None。它將會被設定成所引發例外的 __cause__。設定 __cause__ 也隱含地設定 __suppress_context__ 屬性為 True,因此使用 raise new_exc from None 實際上會以新的例外取代舊的例外以利於顯示(例如轉換 KeyErrorAttributeError),同時保持舊的例外可以透過 __context__ 取得以方便 debug 的時候檢查。

預設的回溯 (traceback) 顯示程式碼會顯示這些連鎖的例外 (chained exception) 加上例外本身的回溯。當存在的時候,在 __cause__ 中明確地連鎖的例外總是會被顯示。而在 __context__ 中隱含地連鎖的例外只有當 __cause__None__suppress_context__ 是 false 時才會顯示。

在任一種情況下,例外本身總是會顯示在任何連鎖例外的後面,因此回溯的最後一行總是顯示最後一個被引發的例外。

繼承自內建的例外

使用者的程式碼可以建立繼承自例外類型的子類別。建議一次只繼承一種例外類型以避免在基底類別之間如何處理 args 屬性的任何可能衝突,以及可能的記憶體佈局 (memory layout) 不相容。

CPython 實作細節: 為了效率,大部分的內建例外使用 C 來實作,參考 Objects/exceptions.c。一些例外有客製化的記憶體佈局,使其不可能建立一個繼承多種例外類型的子類別。類型的記憶體佈局是實作細節且可能會在不同 Python 版本間改變,造成未來新的衝突。因此,總之建議避免繼承多種例外類型。

基底類別 (base classes)

以下的例外大部分被用在當作其他例外的基底類別。

exception BaseException

所有內建例外的基底類別。這不是為了讓使用者定義的類別直接繼承(可以使用 Exception)。如果在這個類別的實例上呼叫 str(),會回傳實例的引數的表示,或者沒有引數的時候會回傳空字串。

args

提供給該例外建構函式的引數元組。一些內建的例外(像是 OSError)預期接受特定數量的引數並賦予該元組的每一個元素一個特別的意義,其他例外則通常用一個提供錯誤訊息的單一字串來呼叫。

with_traceback(tb)

此方法設定 tb 為該例外的新的回溯並回傳該例外物件。在 PEP 3134 的例外連鎖功能變得可用之前,此方法曾被更普遍使用。下面的範例顯示我們如何將 SomeException 的實例轉換為 OtherException 的實例同時保留回溯。一旦被引發,目前的 frame 會被加進 OtherException 的回溯,就像原來 SomeException 的回溯會發生的一樣,我們允許它被傳遞給呼叫者:

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

可寫入的欄位,儲存關聯到該例外的回溯物件。也可以參考 The raise statement

add_note(note)

新增字串 note 到例外的備註,在標準的回溯裡,備註出現在例外字串的後面。如果 note 不是字串則引發 TypeError

Added in version 3.11.

__notes__

該例外的備註串列,使用 add_note() 來新增。此屬性在 add_note() 被呼叫的時候建立。

Added in version 3.11.

exception Exception

所有內建、非系統退出 (non-system-exiting) 的例外都衍生自此類別。所有使用者定義的例外應該也要衍生自此類別。

exception ArithmeticError

各種運算錯誤所引發的那些內建例外:OverflowErrorZeroDivisionErrorFloatingPointError 的基底類別。

exception BufferError

緩衝 (buffer) 相關的操作無法被執行時會引發此例外。

exception LookupError

當使用在對映或序列上的鍵或索引是無效的時候所引發的例外:IndexErrorKeyError 的基底類別。這可以被 codecs.lookup() 直接引發。

實體例外

以下的例外是通常會被引發的例外。

exception AssertionError

assert 陳述式失敗的時候被引發。

exception AttributeError

當屬性參照(參考 Attribute references)或賦值失敗的時候被引發。(當物件根本不支援屬性參照或屬性賦值的時候,TypeError 會被引發。)

nameobj 屬性可以使用建構函式的僅限關鍵字 (keyword-only) 引數來設定。當被設定的時候,它們分別代表被嘗試存取的屬性名稱以及被以該屬性存取的物件。

在 3.10 版的變更: 新增 nameobj 屬性。

exception EOFError

input() 函式在沒有讀到任何資料而到達檔案結尾 (end-of-file, EOF) 條件的時候被引發。(注意:io.IOBase.read()io.IOBase.readline() 方法當達到 EOF 時會回傳空字串。)

exception FloatingPointError

目前沒有被使用。

exception GeneratorExit

generatorcoroutine 被關閉的時候被引發;參考 generator.close()coroutine.close()。此例外直接繼承自 BaseException 而不是 Exception,因為技術上來說這不是一個錯誤。

exception ImportError

import 陳述式嘗試載入模組遇到問題的時候會被引發。當 from import 裡的 “from list” 包含找不到的名稱時也會被引發。

可選的僅限關鍵字引數 namepath 設定對應的屬性:

name

嘗試引入 (import) 的模組名稱。

path

觸發此例外的任何檔案的路徑。

在 3.3 版的變更: 新增 namepath 屬性。

exception ModuleNotFoundError

ImportError 的子類別,當模組不能被定位的時候會被 import 所引發。當在 sys.modules 裡找到 None 時也會被引發。

Added in version 3.6.

exception IndexError

當序列的索引超出範圍的時候會被引發。(切片索引 (slice indices) 會默默地被截短使其能落在允許的範圍內;如果索引不是整數,TypeError 會被引發。)

exception KeyError

當對映(字典)的鍵無法在已存在的鍵的集合中被找到時會被引發。

exception KeyboardInterrupt

當使用者輸入中斷鍵 (interrupt key)(一般來說是 Control-CDelete)時會被引發。在執行過程中,會定期檢查是否產生中斷。此例外繼承自 BaseException 以防止意外地被捕捉 Exception 的程式碼所捕捉,而因此讓直譯器無法結束。

備註

捕捉 KeyboardInterrupt 需要特殊的考量。因為它可以在無法預期的時間點被引發,可能在某些情況下讓正在跑的程式處在一個不一致的狀態。一般來說最好讓 KeyboardInterrupt 越快結束程式越好,或者完全避免引發它。(參考 Note on Signal Handlers and Exceptions。)

exception MemoryError

當一個操作用光了記憶體但情況還可能被修復 (rescued)(透過刪除一些物件)的時候被引發。關聯的值是一個字串,表示什麼類型的(內部)操作用光了記憶體。需注意的是因為底層的記憶體管理架構(C 的 malloc() 函式),直譯器可能無法總是完整地從該情況中修復;僅管如此,它還是引發例外以讓堆疊回溯可以被印出,以防原因出在失控的程式。

exception NameError

當找不到本地或全域的名稱時會被引發。這只應用在不合格的名稱 (unqualified name) 上。關聯的值是一個錯誤訊息,包含那個無法被找到的名稱。

name 屬性可以使用僅限關鍵字引數來設定到建構函式。當被設定的時候它代表被嘗試存取的變數名稱。

在 3.10 版的變更: 新增 name 屬性。

exception NotImplementedError

This exception is derived from RuntimeError. In user defined base classes, abstract methods should raise this exception when they require derived classes to override the method, or while the class is being developed to indicate that the real implementation still needs to be added.

備註

It should not be used to indicate that an operator or method is not meant to be supported at all -- in that case either leave the operator / method undefined or, if a subclass, set it to None.

備註

NotImplementedError and NotImplemented are not interchangeable, even though they have similar names and purposes. See NotImplemented for details on when to use it.

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

This exception is raised when a system function returns a system-related error, including I/O failures such as "file not found" or "disk full" (not for illegal argument types or other incidental errors).

The second form of the constructor sets the corresponding attributes, described below. The attributes default to None if not specified. For backwards compatibility, if three arguments are passed, the args attribute contains only a 2-tuple of the first two constructor arguments.

The constructor often actually returns a subclass of OSError, as described in OS exceptions below. The particular subclass depends on the final errno value. This behaviour only occurs when constructing OSError directly or via an alias, and is not inherited when subclassing.

errno

A numeric error code from the C variable errno.

winerror

Under Windows, this gives you the native Windows error code. The errno attribute is then an approximate translation, in POSIX terms, of that native error code.

Under Windows, if the winerror constructor argument is an integer, the errno attribute is determined from the Windows error code, and the errno argument is ignored. On other platforms, the winerror argument is ignored, and the winerror attribute does not exist.

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

For exceptions that involve a file system path (such as open() or os.unlink()), filename is the file name passed to the function. For functions that involve two file system paths (such as os.rename()), filename2 corresponds to the second file name passed to the function.

在 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 版的變更: The filename attribute is now the original file name passed to the function, instead of the name encoded to or decoded from the filesystem encoding and error handler. Also, the filename2 constructor argument and attribute was added.

exception OverflowError

Raised when the result of an arithmetic operation is too large to be represented. This cannot occur for integers (which would rather raise MemoryError than give up). However, for historical reasons, OverflowError is sometimes raised for integers that are outside a required range. Because of the lack of standardization of floating point exception handling in C, most floating point operations are not checked.

exception RecursionError

This exception is derived from RuntimeError. It is raised when the interpreter detects that the maximum recursion depth (see sys.getrecursionlimit()) is exceeded.

Added in version 3.5: Previously, a plain RuntimeError was raised.

exception ReferenceError

This exception is raised when a weak reference proxy, created by the weakref.proxy() function, is used to access an attribute of the referent after it has been garbage collected. For more information on weak references, see the weakref module.

exception RuntimeError

Raised when an error is detected that doesn't fall in any of the other categories. The associated value is a string indicating what precisely went wrong.

exception StopIteration

Raised by built-in function next() and an iterator's __next__() method to signal that there are no further items produced by the iterator.

value

The exception object has a single attribute value, which is given as an argument when constructing the exception, and defaults to None.

When a generator or coroutine function returns, a new StopIteration instance is raised, and the value returned by the function is used as the value parameter to the constructor of the exception.

If a generator code directly or indirectly raises StopIteration, it is converted into a RuntimeError (retaining the StopIteration as the new exception's cause).

在 3.3 版的變更: Added value attribute and the ability for generator functions to use it to return a value.

在 3.5 版的變更: Introduced the RuntimeError transformation via from __future__ import generator_stop, see PEP 479.

在 3.7 版的變更: Enable PEP 479 for all code by default: a StopIteration error raised in a generator is transformed into a RuntimeError.

exception StopAsyncIteration

Must be raised by __anext__() method of an asynchronous iterator object to stop the iteration.

Added in version 3.5.

exception SyntaxError(message, details)

Raised when the parser encounters a syntax error. This may occur in an import statement, in a call to the built-in functions compile(), exec(), or eval(), or when reading the initial script or standard input (also interactively).

The str() of the exception instance returns only the error message. Details is a tuple whose members are also available as separate attributes.

filename

The name of the file the syntax error occurred in.

lineno

Which line number in the file the error occurred in. This is 1-indexed: the first line in the file has a lineno of 1.

offset

The column in the line where the error occurred. This is 1-indexed: the first character in the line has an offset of 1.

text

The source code text involved in the error.

end_lineno

Which line number in the file the error occurred ends in. This is 1-indexed: the first line in the file has a lineno of 1.

end_offset

The column in the end line where the error occurred finishes. This is 1-indexed: the first character in the line has an offset of 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_linenoend_offset 屬性。

exception IndentationError

Base class for syntax errors related to incorrect indentation. This is a subclass of SyntaxError.

exception TabError

Raised when indentation contains an inconsistent use of tabs and spaces. This is a subclass of 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).

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.

A call to sys.exit() is translated into an exception so that clean-up handlers (finally clauses of try statements) can be executed, and so that a debugger can execute a script without running the risk of losing control. The os._exit() function can be used if it is absolutely positively necessary to exit immediately (for example, in the child process after a call to os.fork()).

code

The exit status or error message that is passed to the constructor. (Defaults to None.)

exception TypeError

Raised when an operation or function is applied to an object of inappropriate type. The associated value is a string giving details about the type mismatch.

This exception may be raised by user code to indicate that an attempted operation on an object is not supported, and is not meant to be. If an object is meant to support a given operation but has not yet provided an implementation, NotImplementedError is the proper exception to raise.

Passing arguments of the wrong type (e.g. passing a list when an int is expected) should result in a TypeError, but passing arguments with the wrong value (e.g. a number outside expected boundaries) should result in a ValueError.

exception UnboundLocalError

Raised when a reference is made to a local variable in a function or method, but no value has been bound to that variable. This is a subclass of NameError.

exception UnicodeError

Raised when a Unicode-related encoding or decoding error occurs. It is a subclass of ValueError.

UnicodeError has attributes that describe the encoding or decoding error. For example, err.object[err.start:err.end] gives the particular invalid input that the codec failed on.

encoding

The name of the encoding that raised the error.

reason

A string describing the specific codec error.

object

The object the codec was attempting to encode or decode.

start

The first index of invalid data in object.

end

The index after the last invalid data in object.

exception UnicodeEncodeError

Raised when a Unicode-related error occurs during encoding. It is a subclass of UnicodeError.

exception UnicodeDecodeError

Raised when a Unicode-related error occurs during decoding. It is a subclass of UnicodeError.

exception UnicodeTranslateError

Raised when a Unicode-related error occurs during translating. It is a subclass of UnicodeError.

exception ValueError

Raised when an operation or function receives an argument that has the right type but an inappropriate value, and the situation is not described by a more precise exception such as IndexError.

exception ZeroDivisionError

Raised when the second argument of a division or modulo operation is zero. The associated value is a string indicating the type of the operands and the operation.

The following exceptions are kept for compatibility with previous versions; starting from Python 3.3, they are aliases of OSError.

exception EnvironmentError
exception IOError
exception WindowsError

僅限於在 Windows 中使用。

OS exceptions

The following exceptions are subclasses of OSError, they get raised depending on the system error code.

exception BlockingIOError

Raised when an operation would block on an object (e.g. socket) set for non-blocking operation. Corresponds to errno EAGAIN, EALREADY, EWOULDBLOCK and EINPROGRESS.

In addition to those of OSError, BlockingIOError can have one more attribute:

characters_written

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

exception ChildProcessError

Raised when an operation on a child process failed. Corresponds to errno ECHILD.

exception ConnectionError

A base class for connection-related issues.

Subclasses are BrokenPipeError, ConnectionAbortedError, ConnectionRefusedError and ConnectionResetError.

exception BrokenPipeError

A subclass of ConnectionError, raised when trying to write on a pipe while the other end has been closed, or trying to write on a socket which has been shutdown for writing. Corresponds to errno EPIPE and ESHUTDOWN.

exception ConnectionAbortedError

A subclass of ConnectionError, raised when a connection attempt is aborted by the peer. Corresponds to errno ECONNABORTED.

exception ConnectionRefusedError

A subclass of ConnectionError, raised when a connection attempt is refused by the peer. Corresponds to errno ECONNREFUSED.

exception ConnectionResetError

A subclass of ConnectionError, raised when a connection is reset by the peer. Corresponds to errno ECONNRESET.

exception FileExistsError

Raised when trying to create a file or directory which already exists. Corresponds to errno EEXIST.

exception FileNotFoundError

Raised when a file or directory is requested but doesn't exist. Corresponds to errno ENOENT.

exception InterruptedError

Raised when a system call is interrupted by an incoming signal. Corresponds to errno EINTR.

在 3.5 版的變更: Python now retries system calls when a syscall is interrupted by a signal, except if the signal handler raises an exception (see PEP 475 for the rationale), instead of raising InterruptedError.

exception IsADirectoryError

Raised when a file operation (such as os.remove()) is requested on a directory. Corresponds to errno EISDIR.

exception NotADirectoryError

Raised when a directory operation (such as os.listdir()) is requested on something which is not a directory. On most POSIX platforms, it may also be raised if an operation attempts to open or traverse a non-directory file as if it were a directory. Corresponds to errno ENOTDIR.

exception PermissionError

Raised when trying to run an operation without the adequate access rights - for example filesystem permissions. Corresponds to errno EACCES, EPERM, and ENOTCAPABLE.

在 3.11.1 版的變更: WASI's ENOTCAPABLE is now mapped to PermissionError.

exception ProcessLookupError

Raised when a given process doesn't exist. Corresponds to errno ESRCH.

exception TimeoutError

Raised when a system function timed out at the system level. Corresponds to errno ETIMEDOUT.

Added in version 3.3: All the above OSError subclasses were added.

也參考

PEP 3151 - Reworking the OS and IO exception hierarchy

警告

The following exceptions are used as warning categories; see the Warning Categories documentation for more details.

exception Warning

Base class for warning categories.

exception UserWarning

Base class for warnings generated by user code.

exception DeprecationWarning

Base class for warnings about deprecated features when those warnings are intended for other Python developers.

Ignored by the default warning filters, except in the __main__ module (PEP 565). Enabling the Python Development Mode shows this warning.

The deprecation policy is described in PEP 387.

exception PendingDeprecationWarning

Base class for warnings about features which are obsolete and expected to be deprecated in the future, but are not deprecated at the moment.

This class is rarely used as emitting a warning about a possible upcoming deprecation is unusual, and DeprecationWarning is preferred for already active deprecations.

Ignored by the default warning filters. Enabling the Python Development Mode shows this warning.

The deprecation policy is described in PEP 387.

exception SyntaxWarning

Base class for warnings about dubious syntax.

exception RuntimeWarning

Base class for warnings about dubious runtime behavior.

exception FutureWarning

Base class for warnings about deprecated features when those warnings are intended for end users of applications that are written in Python.

exception ImportWarning

Base class for warnings about probable mistakes in module imports.

Ignored by the default warning filters. Enabling the Python Development Mode shows this warning.

exception UnicodeWarning

Base class for warnings related to Unicode.

exception EncodingWarning

Base class for warnings related to encodings.

細節請見 選擇性加入的編碼警告

Added in version 3.10.

exception BytesWarning

Base class for warnings related to bytes and bytearray.

exception ResourceWarning

Base class for warnings related to resource usage.

Ignored by the default warning filters. Enabling the Python Development Mode shows this warning.

Added in version 3.2.

Exception groups

The following are used when it is necessary to raise multiple unrelated exceptions. They are part of the exception hierarchy so they can be handled with except like all other exceptions. In addition, they are recognised by except*, which matches their subgroups based on the types of the contained exceptions.

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

Both of these exception types wrap the exceptions in the sequence excs. The msg parameter must be a string. The difference between the two classes is that BaseExceptionGroup extends BaseException and it can wrap any exception, while ExceptionGroup extends Exception and it can only wrap subclasses of Exception. This design is so that except Exception catches an ExceptionGroup but not BaseExceptionGroup.

The BaseExceptionGroup constructor returns an ExceptionGroup rather than a BaseExceptionGroup if all contained exceptions are Exception instances, so it can be used to make the selection automatic. The ExceptionGroup constructor, on the other hand, raises a TypeError if any contained exception is not an Exception subclass.

message

The msg argument to the constructor. This is a read-only attribute.

exceptions

A tuple of the exceptions in the excs sequence given to the constructor. This is a read-only attribute.

subgroup(condition)

Returns an exception group that contains only the exceptions from the current group that match condition, or None if the result is empty.

The condition can be either a function that accepts an exception and returns true for those that should be in the subgroup, or it can be an exception type or a tuple of exception types, which is used to check for a match using the same check that is used in an except clause.

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.

split(condition)

Like subgroup(), but returns the pair (match, rest) where match is subgroup(condition) and rest is the remaining non-matching part.

derive(excs)

Returns an exception group with the same message, but which wraps the exceptions in excs.

This method is used by subgroup() and split(). A subclass needs to override it in order to make subgroup() and split() return instances of the subclass rather than ExceptionGroup.

subgroup() and split() copy the __traceback__, __cause__, __context__ and __notes__ fields from the original exception group to the one returned by derive(), so these fields do not need to be updated by 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 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
      │    └── 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