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 技術手冊 第三版
188
|
5 章 例外
ValueError
一個運算或函式被套用到了型別正確的物件,但值不合適,而且沒有
更特定的例外(例如
KeyError
)適用。
WindowsError
由模組
os
(涵蓋於後面的「os 模組」以及「以 os 模組執行其他
程式」)中的函式所提出,用以表示 Windows 限定的錯誤。擴充
OSError
ZeroDivisionError
有一個除數(
/
//
%
運算子右手邊的運算元,或內建函式
divmod
第二個引數)是
0
。擴充
ArithmeticError
OSError 和子類別(僅限 v3
v3 中,
OSError
收納了v2 分開來放的許多錯誤,例如
IOError
socket.error
。為了補償(以及更多原因!),在 v3
OSError
衍生了許多
實用的子類別,你能夠捕捉它們,以更為優雅的方式處理環境錯誤,參閱
線上文件(
https://docs.python.org/3/library/exceptions.html#os-exceptions
)。
舉例來說,請考慮這項任務:試著讀取並回傳一個特定檔案的內容,如果
檔案不存在就回傳一個預設的字串,傳播使該檔案無法讀的其他任何例外
(除了檔案不存在以外的那些)。一個 v2/v3 可移植的版本:
import errno
def read_or_default(filepath, default):
try:
with open(filepath) as f:
return f.read()
except IOError ...
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