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

Python 技術手冊 第三版

by lex Martelli, Anna Martelli Ravenscroft, Steve Holden
January 2018
Intermediate 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.

Read now

Unlock full access

More than 5,000 organizations count on O’Reilly

AirBnbBlueOriginElectronic ArtsHomeDepotNasdaqRakutenTata Consultancy Services

QuotationMarkO’Reilly covers everything we've got, with content to help us build a world-class technology community, upgrade the capabilities and competencies of our teams, and improve overall team performance as well as their engagement.
Julian F.
Head of Cybersecurity
QuotationMarkI wanted to learn C and C++, but it didn't click for me until I picked up an O'Reilly book. When I went on the O’Reilly platform, I was astonished to find all the books there, plus live events and sandboxes so you could play around with the technology.
Addison B.
Field Engineer
QuotationMarkI’ve been on the O’Reilly platform for more than eight years. I use a couple of learning platforms, but I'm on O'Reilly more than anybody else. When you're there, you start learning. I'm never disappointed.
Amir M.
Data Platform Tech Lead
QuotationMarkI'm always learning. So when I got on to O'Reilly, I was like a kid in a candy store. There are playlists. There are answers. There's on-demand training. It's worth its weight in gold, in terms of what it allows me to do.
Mark W.
Embedded Software Engineer

You might also like

利用 Python 进行数据分析(原书第2版)

利用 Python 进行数据分析(原书第2版)

Wes McKinney

Publisher Resources

ISBN: 9789864766819