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 技術手冊 第三版
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.
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