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 技術手冊 第三版
180
|
5 章 例外
產生器與例外
為了幫助產生器(generators)與例外合作,
yield
述句也被允許放在
try/
finally
述句內。此外,產生器物件還有另外兩個相關的方法
throw
close
。給定一個產生器物件
g
(呼叫一個產生器函式所建置),
throw
方法
的特徵式(signature)在 v2 中是:
g.throw(exc_type, exc_value=None, exc_traceback=None)
v3 中則更為簡單:
g.throw(exc_value)
當產生器的呼叫者呼叫
g.throw
,其效果就好像帶有相同引數的一個
raise
述句在
yield
的位置(產生器
g
暫停的地方)被執行。
產生器方法
close
沒有引數,當產生器的呼叫者呼叫
g.close()
,效果就像
是呼叫
g.throw(GeneratorExit())
GeneratorExit
是一個內建的例外類別,
它直接繼承自
BaseException
。一個產生器的
close
方法應該在進行了產生
器可能需要的任何清理工作之後,重新提出(或傳播)這個
GeneratorExit
例外。產生器也有一個最終處理器(特殊方法
__del__
)與方法
close
完全
等效。
例外傳播
當一個例外被提出,例外傳播機制(exception-propagation mechanism)就
會接管控制。程式正常的控制流程就會停止,而 Python 會尋找一個適合的
例外處理器(exception handler)。 Python
try
述句藉由它的 ...
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