Skip to Content
Python 技術手冊 第三版
book

Python 技術手冊 第三版

by lex Martelli, Anna Martelli Ravenscroft, Steve Holden
January 2018
Intermediate to advanced content levelIntermediate to advanced
856 pages
17h 17m
Chinese
GoTop Information, Inc.
Content preview from Python 技術手冊 第三版
173
5
例外
Python 使用例外(exceptions)來傳達錯誤與異常狀況。一個
例外
exception
是代表錯誤(error)或異常(anomaly)的一種物件。當
Python 偵測到錯誤,它會
提出
raises
一個例外,也就是說,Python
傳遞一個例外物件給例外傳播機制(exception-propagation mechanism)作
為有某個異常狀況發生的訊號。你的程式碼能夠執行一個
raise
述句來明
確地提出一個例外。
處理
handling
一個例外代表從傳播機制接收例外物件,並且進行應付
那個異常狀況所需的任何動作。如果一個程式沒有處理一個例外,那個程
式就會以錯誤追溯訊息(error traceback message)終止。不過一個程式可
以處理例外,以在有錯誤或其他異常狀況發生時,繼續執行。
Python 也使用例外來表示某些不是錯誤,甚至不算異常的特殊情況。舉例
來說,如前面「迭代器」中所涵蓋的,當一個迭代器已經沒有更多的項目
可提供時,對它呼叫
next
內建函式會提出
StopIteration
例外。這並非一
個錯誤,甚至不是異常狀況,因為大多數的迭代器最終都會耗盡項目。因
此在 Python 中檢查和處理錯誤及其他特殊情況的最佳策略會跟其他語言中
最好的不同,而我們會在後面的「錯誤檢查策略」中涵蓋那些考量。本章
也在後面的「記錄錯誤」中涵蓋 Python 標準程式庫的
logging
模組,並在
assert 述句」中涵蓋 Python
assert
述句。
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

測試驅動開發|使用 Python

測試驅動開發|使用 Python

Harry J.W. Percival
Linux 内核观测技术BPF

Linux 内核观测技术BPF

David Calavera, Lorenzo Fontana

Publisher Resources

ISBN: 9789864766819