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 技術手冊 第三版
192
|
5 章 例外
為自訂例外使用多重繼承
每當你必須決定是要提出一個特定的標準例外,例如
AttributeError
,還是你在你模組中定義的一個自訂例外,
那就考慮這種多重繼承的做法,它能讓你兩者兼顧。請確
保你有在說明文件中清楚記載你模組的這個層面,因為這
個技巧並沒有廣泛被使用,你模組的使用者可能沒有如此
預期,除非你清楚且明確的記錄在文件中。
標準程式庫中所使用的其他例外
Python 標準程式庫中的許多模組都定義有它們自己的例外類別,它們與你
自己的模組可以定義的自訂例外類別有相同的效果。一般來說,這種標準
程式庫模組中的所有函式,除了標準階層架構(涵蓋於前面的「標準例外
類別」)中的例外,也可以提出這種類別的例外。舉例來說,在 v2 中,模
socket
提供了類別
socket.error
,它直接衍生自內建類別
Exception
,還
error
的數個子類別
sslerror
timeout
gaierror
herror
模組
socket
中的所有函式與方法,除了標準例外之外,也可以提出類別
socket.error
及其子類別的例外。我們會在本書其餘部分的各處涵蓋這種
例外類別的主要案例,在提供它們的標準程式庫模組的章節中。
錯誤檢查策略
支援例外的多數程式語言只會在少數情況下提出例外。Python 所強調的重
點則不同。Python 會在例外使得程式更為簡單而且更穩健的時候運用它
們,即使那會讓例外變得相當頻繁。
LBYL vs. EAFP
其他語言中一個常見的慣用語(idiom),有時叫做「
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