內置異常?

在 Python 中,所有異常必須為一個派生自 BaseException 的類的實例。 在帶有提及一個特定類的 except 子句的 try 語句中,該子句也會處理任何派生自該類的異常類(但不處理 所派生出的異常類)。 通過子類化創(chuàng)建的兩個不相關異常類永遠是不等效的,既使它們具有相同的名稱。

下面列出的內置異??赏ㄟ^解釋器或內置函數來生成。除非另有說明,它們都會具有一個提示導致錯誤詳細原因的“關聯值”。 這可以是一個字符串或由多個信息項(例如一個錯誤碼和一個解釋錯誤的字符串)組成的元組。 關聯值通常會作為參數被傳遞給異常類的構造器。

用戶代碼可以引發(fā)內置異常。 這可被用于測試異常處理程序或報告錯誤條件,“就像” 在解釋器引發(fā)了相同異常的情況時一樣;但是請注意,沒有任何機制能防止用戶代碼引發(fā)不適當的錯誤。

內置異常類可以被子類化以定義新的異常;鼓勵程序員從 Exception 類或它的某個子類而不是從 BaseException 來派生新的異常。 關于定義異常的更多信息可以在 Python 教程的 用戶自定義異常 部分查看。

Exception 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。 它將在所引發(fā)的異常上被設置為 __cause__。 設置 __cause__ 還會隱式地將 __suppress_context__ 屬性設為 True,這樣使用 raise new_exc from None 可以有效地將舊異常替換為新異常來顯示其目的 (例如將 KeyError 轉換為 AttributeError),同時讓舊異常在 __context__ 中保持可用狀態(tài)以便在調試時進行內省。

除了異常本身的回溯以外,默認的回溯還會顯示這些串連的異常。 __cause__ 中的顯式串連異常如果存在將總是顯示。 __context__ 中的隱式串連異常僅在 __cause__None 并且 __suppress_context__ 為假值時顯示。

不論在哪種情況下,異常本身總會在任何串連異常之后顯示,以便回溯的最后一行總是顯示所引發(fā)的最后一個異常。

Inheriting from built-in exceptions?

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 implementation detail: 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)?

此方法會將 tb 設為新的異常回溯信息并返回異常對象。 它在 PEP 3134 的異常鏈特性可用之前更為常用。 下面的例子演示了我們如何將一個 SomeException 實例轉換為 OtherException 實例而保留回溯信息。 異常一旦被引發(fā),當前幀會被推至 OtherException 的回溯棧頂端,就像當我們允許原始 SomeException 被傳播給調用方時它的回溯棧將會發(fā)生的情形一樣。:

try:
    ...
except SomeException:
    tb = sys.exc_info()[2]
    raise OtherException(...).with_traceback(tb)
add_note(note)?

Add the string note to the exception's notes which appear in the standard traceback after the exception string. A TypeError is raised if note is not a string.

3.11 新版功能.

__notes__?

A list of the notes of this exception, which were added with add_note(). This attribute is created when add_note() is called.

3.11 新版功能.

exception Exception?

所有內置的非系統退出類異常都派生自此類。 所有用戶自定義異常也應當派生自此類。

exception ArithmeticError?

此基類用于派生針對各種算術類錯誤而引發(fā)的內置異常: OverflowError, ZeroDivisionError, FloatingPointError。

exception BufferError?

當與 緩沖區(qū) 相關的操作無法執(zhí)行時將被引發(fā)。

exception LookupError?

此基類用于派生當映射或序列所使用的鍵或索引無效時引發(fā)的異常: IndexError, KeyError。 這可以通過 codecs.lookup() 來直接引發(fā)。

具體異常?

以下異常屬于經常被引發(fā)的異常。

exception AssertionError?

assert 語句失敗時將被引發(fā)。

exception AttributeError?

當屬性引用 (參見 屬性引用) 或賦值失敗時將被引發(fā)。 (當一個對象根本不支持屬性引用或屬性賦值時則將引發(fā) TypeError。)

nameobj 屬性可以使用構造器的僅限關鍵字參數來設置。 它們如果被設置則分別代表要嘗試訪問的屬性名稱以及所訪問的該屬性的對象。

在 3.10 版更改: 增加了 nameobj 屬性。

exception EOFError?

input() 函數未讀取任何數據即達到文件結束條件 (EOF) 時將被引發(fā)。 (另外,io.IOBase.read()io.IOBase.readline() 方法在遇到 EOF 則將返回一個空字符串。)

exception FloatingPointError?

目前未被使用。

exception GeneratorExit?

當一個 generatorcoroutine 被關閉時將被引發(fā);參見 generator.close()coroutine.close()。 它直接繼承自 BaseException 而不是 Exception,因為從技術上來說它并不是一個錯誤。

exception ImportError?

import 語句嘗試加載模塊遇到麻煩時將被引發(fā)。 并且當 from ... import 中的 "from list" 存在無法找到的名稱時也會被引發(fā)。

namepath 屬性可通過對構造器使用僅關鍵字參數來設定。 設定后它們將分別表示被嘗試導入的模塊名稱與觸發(fā)異常的任意文件所在路徑。

在 3.3 版更改: 添加了 namepath 屬性。

exception ModuleNotFoundError?

ImportError 的子類,當一個模塊無法被定位時將由 import 引發(fā)。 當在 sys.modules 中找到 None 時也會被引發(fā)。

3.6 新版功能.

exception IndexError?

當序列抽取超出范圍時將被引發(fā)。 (切片索引會被靜默截短到允許的范圍;如果指定索引不是整數則 TypeError 會被引發(fā)。)

exception KeyError?

當在現有鍵集合中找不到指定的映射(字典)鍵時將被引發(fā)。

exception KeyboardInterrupt?

當用戶按下中斷鍵 (通常為 Control-CDelete) 時將被引發(fā)。 在執(zhí)行期間,會定期檢測中斷信號。 該異常繼承自 BaseException 以確保不會被處理 Exception 的代碼意外捕獲,這樣可以避免退出解釋器。

備注

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?

當一個操作耗盡內存但情況仍可(通過刪除一些對象)進行挽救時將被引發(fā)。 關聯的值是一個字符串,指明是哪種(內部)操作耗盡了內存。 請注意由于底層的內存管理架構(C 的 malloc() 函數),解釋器也許并不總是能夠從這種情況下完全恢復;但它畢竟可以引發(fā)一個異常,這樣就能打印出?;厮菪畔?,以便找出導致問題的失控程序。

exception NameError?

當某個局部或全局名稱未找到時將被引發(fā)。 此異常僅用于非限定名稱。 關聯的值是一條錯誤信息,其中包含未找到的名稱。

name 屬性可以使用構造器的僅限關鍵字參數來設置。 它如果被設置則代表要嘗試訪問的變量名稱。

在 3.10 版更改: 增加了 name 屬性。

exception NotImplementedError?

此異常派生自 RuntimeError。 在用戶自定義的基類中,抽象方法應當在其要求所派生類重載該方法,或是在其要求所開發(fā)的類提示具體實現尚待添加時引發(fā)此異常。

備注

它不應當用來表示一個運算符或方法根本不能被支持 -- 在此情況下應當讓特定運算符 / 方法保持未定義,或者在子類中將其設為 None

備注

NotImplementedErrorNotImplemented 不可互換,即使它們有相似的名稱和用途。 請參閱 NotImplemented 了解有關何時使用它們的詳細說明。

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

此異常在一個系統函數返回系統相關的錯誤時將被引發(fā),此類錯誤包括 I/O 操作失敗例如 "文件未找到" 或 "磁盤已滿" 等(不包括非法參數類型或其他偶然性錯誤)。

構造器的第二種形式可設置如下所述的相應屬性。 如果未指定這些屬性則默認為 None。 為了能向下兼容,如果傳入了三個參數,則 args 屬性將僅包含由前兩個構造器參數組成的 2 元組。

構造器實際返回的往往是 OSError 的某個子類,如下文 OS exceptions 中所描述的。 具體的子類取決于最終的 errno 值。 此行為僅在直接或通過別名來構造 OSError 時發(fā)生,并且在子類化時不會被繼承。

errno?

來自于 C 變量 errno 的數字錯誤碼。

winerror?

在 Windows 下,此參數將給出原生的 Windows 錯誤碼。 而 errno 屬性將是該原生錯誤碼在 POSIX 平臺下的近似轉換形式。

在 Windows 下,如果 winerror 構造器參數是一個整數,則 errno 屬性會根據 Windows 錯誤碼來確定,而 errno 參數會被忽略。 在其他平臺上,winerror 參數會被忽略,并且 winerror 屬性將不存在。

strerror?

操作系統所提供的相應錯誤信息。 它在 POSIX 平臺中由 C 函數 perror() 來格式化,在 Windows 中則是由 FormatMessage()。

filename?
filename2?

對于與文件系統路徑有關 (例如 open()os.unlink()) 的異常,filename 是傳給函數的文件名。 對于涉及兩個文件系統路徑的函數 (例如 os.rename()),filename2 將是傳給函數的第二個文件名。

在 3.3 版更改: EnvironmentError, IOError, WindowsError, socket.error, select.errormmap.error 已被合并到 OSError,構造器可能返回其中一個子類。

在 3.4 版更改: filename 屬性現在是傳給函數的原始文件名,而不是基于 filesystem encoding and error handler 進行編碼或解碼之后的名稱。 此外,還添加了 filename2 構造器參數和屬性。

exception OverflowError?

當算術運算的結果大到無法表示時將被引發(fā)。 這對整數來說不可能發(fā)生(寧可引發(fā) MemoryError 也不會放棄嘗試)。 但是出于歷史原因,有時也會在整數超出要求范圍的情況下引發(fā) OverflowError。 因為在 C 中缺少對浮點異常處理的標準化,大多數浮點運算都不會做檢查。

exception RecursionError?

此異常派生自 RuntimeError。 它會在解釋器檢測發(fā)現超過最大遞歸深度 (參見 sys.getrecursionlimit()) 時被引發(fā)。

3.5 新版功能: 在此之前將只引發(fā) RuntimeError。

exception ReferenceError?

此異常將在使用 weakref.proxy() 函數所創(chuàng)建的弱引用來訪問該引用的某個已被作為垃圾回收的屬性時被引發(fā)。 有關弱引用的更多信息請參閱 weakref 模塊。

exception RuntimeError?

當檢測到一個不歸屬于任何其他類別的錯誤時將被引發(fā)。 關聯的值是一個指明究竟發(fā)生了什么問題的字符串。

exception StopIteration?

由內置函數 next()iterator__next__() 方法所引發(fā),用來表示該迭代器不能產生下一項。

該異常對象只有一個屬性 value,它在構造該異常時作為參數給出,默認值為 None。

當一個 generatorcoroutine 函數返回時,將引發(fā)一個新的 StopIteration 實例,函數返回的值將被用作異常構造器的 value 形參。

如果某個生成器代碼直接或間接地引發(fā)了 StopIteration,它會被轉換為 RuntimeError (并將 StopIteration 保留為導致新異常的原因)。

在 3.3 版更改: 添加了 value 屬性及其被生成器函數用作返回值的功能。

在 3.5 版更改: 引入了通過 from __future__ import generator_stop 來實現 RuntimeError 轉換,參見 PEP 479。

在 3.7 版更改: 默認對所有代碼啟用 PEP 479: 在生成器中引發(fā)的 StopIteration 錯誤將被轉換為 RuntimeError。

exception StopAsyncIteration?

必須由一個 asynchronous iterator 對象的 __anext__() 方法來引發(fā)以停止迭代操作。

3.5 新版功能.

exception SyntaxError(message, details)?

當解析器遇到語法錯誤時引發(fā)。 這可以發(fā)生在 import 語句,對內置函數 compile(), exec()eval() 的調用,或是讀取原始腳本或標準輸入(也包括交互模式)的時候。

異常實例的 str() 只返回錯誤消息。 錯誤詳情為一個元組,其成員也可在單獨的屬性中分別獲取。

filename?

發(fā)生語法錯誤所在文件的名稱。

lineno?

發(fā)生錯誤所在文件中的行號。 行號索引從 1 開始:文件中首行的 lineno 為 1。

offset?

發(fā)生錯誤所在文件中的列號。 列號索引從 1 開始:行中首個字符的 offset 為 1。

text?

錯誤所涉及的源代碼文本。

end_lineno?

發(fā)生的錯誤在文件中的末尾行號。 這個索引是從 1 開始的:文件中首行的 lineno 為 1。

end_offset?

發(fā)生的錯誤在文件中的末尾列號。 這個索引是從 1 開始:行中首個字符的 offset 為 1。

對于 f-字符串字段中的錯誤,消息會帶有 "f-string: " 前綴并且其位置是基于替換表達式構建的文本中的位置。 例如,編譯 f'Bad {a b} field' 將產生這樣的 args 屬性: ('f-string: ...', ('', 1, 2, '(a b)n', 1, 5))。

在 3.10 版更改: 增加了 end_linenoend_offset 屬性。

exception IndentationError?

與不正確的縮進相關的語法錯誤的基類。 這是 SyntaxError 的一個子類。

exception TabError?

當縮進包含對制表符和空格符不一致的使用時將被引發(fā)。 這是 IndentationError 的一個子類。

exception SystemError?

當解釋器發(fā)現內部錯誤,但情況看起來尚未嚴重到要放棄所有希望時將被引發(fā)。 關聯的值是一個指明發(fā)生了什么問題的字符串(表示為低層級的符號)。

你應當將此問題報告給你所用 Python 解釋器的作者或維護人員。 請確認報告 Python 解釋器的版本號 (sys.version; 它也會在交互式 Python 會話開始時被打印出來),具體的錯誤消息(異常所關聯的值)以及可能觸發(fā)該錯誤的程序源碼。

exception SystemExit?

此異常由 sys.exit() 函數引發(fā)。 它繼承自 BaseException 而不是 Exception 以確保不會被處理 Exception 的代碼意外捕獲。 這允許此異常正確地向上傳播并導致解釋器退出。 如果它未被處理,則 Python 解釋器就將退出;不會打印任何棧回溯信息。 構造器接受的可選參數與傳遞給 sys.exit() 的相同。 如果該值為一個整數,則它指明系統退出狀態(tài)碼(會傳遞給 C 的 exit() 函數);如果該值為 None,則退出狀態(tài)碼為零;如果該值為其他類型(例如字符串),則會打印對象的值并將退出狀態(tài)碼設為一。

sys.exit() 的調用會被轉換為一個異常以便能執(zhí)行清理處理程序 (try 語句的 finally 子句),并且使得調試器可以執(zhí)行一段腳本而不必冒失去控制的風險。 如果絕對確實地需要立即退出(例如在調用 os.fork() 之后的子進程中)則可使用 os._exit().

code?

傳給構造器的退出狀態(tài)碼或錯誤信息(默認為 None。)

exception TypeError?

當一個操作或函數被應用于類型不適當的對象時將被引發(fā)。 關聯的值是一個字符串,給出有關類型不匹配的詳情。

此異??梢杂捎脩舸a引發(fā),以表明嘗試對某個對象進行的操作不受支持也不應當受支持。 如果某個對象應當支持給定的操作但尚未提供相應的實現,所要引發(fā)的適當異常應為 NotImplementedError。

傳入參數的類型錯誤 (例如在要求 int 時卻傳入了 list) 應當導致 TypeError,但傳入參數的值錯誤 (例如傳入要求范圍之外的數值) 則應當導致 ValueError

exception UnboundLocalError?

當在函數或方法中對某個局部變量進行引用,但該變量并未綁定任何值時將被引發(fā)。 此異常是 NameError 的一個子類。

exception UnicodeError?

當發(fā)生與 Unicode 相關的編碼或解碼錯誤時將被引發(fā)。 此異常是 ValueError 的一個子類。

UnicodeError 具有一些描述編碼或解碼錯誤的屬性。 例如 err.object[err.start:err.end] 會給出導致編解碼器失敗的特定無效輸入。

encoding?

引發(fā)錯誤的編碼名稱。

reason?

描述特定編解碼器錯誤的字符串。

object?

編解碼器試圖要編碼或解碼的對象。

start?

object 中無效數據的開始位置索引。

end?

object 中無效數據的末尾位置索引(不含)。

exception UnicodeEncodeError?

當在編碼過程中發(fā)生與 Unicode 相關的錯誤時將被引發(fā)。 此異常是 UnicodeError 的一個子類。

exception UnicodeDecodeError?

當在解碼過程中發(fā)生與 Unicode 相關的錯誤時將被引發(fā)。 此異常是 UnicodeError 的一個子類。

exception UnicodeTranslateError?

在轉寫過程中發(fā)生與 Unicode 相關的錯誤時將被引發(fā)。 此異常是 UnicodeError 的一個子類。

exception ValueError?

當操作或函數接收到具有正確類型但值不適合的參數,并且情況不能用更精確的異常例如 IndexError 來描述時將被引發(fā)。

exception ZeroDivisionError?

當除法或取余運算的第二個參數為零時將被引發(fā)。 關聯的值是一個字符串,指明操作數和運算的類型。

下列異常被保留以與之前的版本相兼容;從 Python 3.3 開始,它們都是 OSError 的別名。

exception EnvironmentError?
exception IOError?
exception WindowsError?

限在 Windows 中可用。

OS 異常?

下列異常均為 OSError 的子類,它們將根據系統錯誤代碼被引發(fā)。

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.

除了 OSError 已有的屬性,BlockingIOError 還有一個額外屬性:

characters_written?

一個整數,表示在被阻塞前已寫入到流的字符數。 當使用來自 io 模塊的帶緩沖 I/O 類時此屬性可用。

exception ChildProcessError?

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

exception ConnectionError?

與連接相關問題的基類。

其子類有 BrokenPipeError, ConnectionAbortedError, ConnectionRefusedErrorConnectionResetError

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?

當系統調用被輸入信號中斷時將被引發(fā)。 對應于 errno EINTR。

在 3.5 版更改: 當系統調用被某個信號中斷時,Python 現在會重試系統調用,除非該信號的處理程序引發(fā)了其它異常 (原理參見 PEP 475) 而不是引發(fā) 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 and EPERM.

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.

3.3 新版功能: 添加了以上所有 OSError 的子類。

參見

PEP 3151 - 重寫 OS 和 IO 異常的層次結構

警告?

下列異常被用作警告類別;請參閱 警告類別 文檔了解詳情。

exception Warning?

警告類別的基類。

exception UserWarning?

用戶代碼所產生警告的基類。

exception DeprecationWarning?

如果所發(fā)出的警告是針對其他 Python 開發(fā)者的,則以此作為與已棄用特性相關警告的基類。

會被默認警告過濾器忽略,在 __main__ 模塊中的情況除外 (PEP 565)。 啟用 Python 開發(fā)模式 時會顯示此警告。

The deprecation policy is described in PEP 387.

exception PendingDeprecationWarning?

對于已過時并預計在未來棄用,但目前尚未棄用的特性相關警告的基類。

這個類很少被使用,因為針對未來可能的棄用發(fā)出警告的做法并不常見,而針對當前已有的棄用則推薦使用 DeprecationWarning。

會被默認警告過濾器忽略。 啟用 Python 開發(fā)模式 時會顯示此警告。

The deprecation policy is described in PEP 387.

exception SyntaxWarning?

與模糊的語法相關的警告的基類。

exception RuntimeWarning?

與模糊的運行時行為相關的警告的基類。

exception FutureWarning?

如果所發(fā)出的警告是針對以 Python 所編寫應用的最終用戶的,則以此作為與已棄用特性相關警告的基類。

exception ImportWarning?

與在模塊導入中可能的錯誤相關的警告的基類。

會被默認警告過濾器忽略。 啟用 Python 開發(fā)模式 時會顯示此警告。

exception UnicodeWarning?

與 Unicode 相關的警告的基類。

exception EncodingWarning?

與編碼格式相關的警告的基類。

請參閱 選擇性的 EncodingWarning 來了解詳情。

3.10 新版功能.

exception BytesWarning?

bytesbytearray 相關的警告的基類。

exception ResourceWarning?

資源使用相關警告的基類。

會被默認警告過濾器忽略。 啟用 Python 開發(fā)模式 時會顯示此警告。

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, __traceback__, __cause__, __context__ and __notes__ 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.

>>>
>>> class MyGroup(ExceptionGroup):
...     def derive(self, exc):
...         return MyGroup(self.message, exc)
...
>>> MyGroup("eg", [ValueError(1), TypeError(2)]).split(TypeError)
(MyGroup('eg', [TypeError(2)]), MyGroup('eg', [ValueError(1)]))

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)

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