鍍金池/ 教程/ Python/ <code>try/else</code>從句
<code>open</code>函數(shù)
Python 2系列版本
可迭代對象(Iterable)
異常
在函數(shù)中嵌入裝飾器
你的第一個(gè)裝飾器
上下文管理器(Context managers)
<code>set</code>(集合)數(shù)據(jù)結(jié)構(gòu)
裝飾器類
字典推導(dǎo)式(<code>dict</code> comprehensions)
<code>Reduce</code>
捐贈名單
<code>Filter</code>
<code>try/else</code>從句
*args 的用法
<code>dir</code>
處理異常
<code>else</code>從句
對象自省
For - Else
18. 一行式
Python 3.2及以后版本
Global和Return
基于類的實(shí)現(xiàn)
容器(<code>Collections</code>)
23. 協(xié)程
推薦閱讀
譯者后記
<code>*args</code> 和 <code>**kwargs</code>
**kwargs 的用法
生成器(Generators)
迭代(Iteration)
基于生成器的實(shí)現(xiàn)
將函數(shù)作為參數(shù)傳給另一個(gè)函數(shù)
日志(Logging)
三元運(yùn)算符
<code>inspect</code>模塊
枚舉
Map,F(xiàn)ilter 和 Reduce
各種推導(dǎo)式(comprehensions)
從函數(shù)中返回函數(shù)
列表推導(dǎo)式(<code>list</code> comprehensions)
處理多個(gè)異常
帶參數(shù)的裝飾器
對象變動(Mutation)
22. 目標(biāo)Python2+3
迭代器(Iterator)
虛擬環(huán)境(virtualenv)
<code>__slots__</code>魔法
什么時(shí)候使用它們?
Python/C API
<code>Map</code>
SWIG
授權(quán)(Authorization)
裝飾器
一切皆對象
使用C擴(kuò)展
使用 <code>*args</code> 和 <code>**kwargs</code> 來調(diào)用函數(shù)
17. <code>lambda</code>表達(dá)式
集合推導(dǎo)式(<code>set</code> comprehensions)
<code>type</code>和<code>id</code>
在函數(shù)中定義函數(shù)
<code>finally</code>從句
CTypes
調(diào)試(Debugging)
使用場景
生成器(Generators)
多個(gè)return值
關(guān)于原作者
函數(shù)緩存 (Function caching)
Python進(jìn)階

<code>try/else</code>從句

我們常常想在沒有觸發(fā)異常的時(shí)候執(zhí)行一些代碼。這可以很輕松地通過一個(gè)else從句來達(dá)到。

有人也許問了:如果你只是想讓一些代碼在沒有觸發(fā)異常的情況下執(zhí)行,為啥你不直接把代碼放在try里面呢?
回答是,那樣的話這段代碼中的任意異常都還是會被try捕獲,而你并不一定想要那樣。

大多數(shù)人并不使用else從句,而且坦率地講我自己也沒有大范圍使用。這里是個(gè)例子:

try:
    print('I am sure no exception is going to occur!')
except Exception:
    print('exception')
else:
    # 這里的代碼只會在try語句里沒有觸發(fā)異常時(shí)運(yùn)行,
    # 但是這里的異常將 *不會* 被捕獲
    print('This would only run if no exception occurs. And an error here '
          'would NOT be caught.')
finally:
    print('This would be printed in every case.')

# Output: I am sure no exception is going to occur!
# This would only run if no exception occurs.
# This would be printed in every case.

else從句只會在沒有異常的情況下執(zhí)行,而且它會在finally語句之前執(zhí)行。