鍍金池/ 教程/ Python/ 處理異常
<code>open</code>函數(shù)
Python 2系列版本
可迭代對(duì)象(Iterable)
異常
在函數(shù)中嵌入裝飾器
你的第一個(gè)裝飾器
上下文管理器(Context managers)
<code>set</code>(集合)數(shù)據(jù)結(jié)構(gòu)
裝飾器類
字典推導(dǎo)式(<code>dict</code> comprehensions)
<code>Reduce</code>
捐贈(zèng)名單
<code>Filter</code>
<code>try/else</code>從句
*args 的用法
<code>dir</code>
處理異常
<code>else</code>從句
對(duì)象自省
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ù)的裝飾器
對(duì)象變動(dòng)(Mutation)
22. 目標(biāo)Python2+3
迭代器(Iterator)
虛擬環(huán)境(virtualenv)
<code>__slots__</code>魔法
什么時(shí)候使用它們?
Python/C API
<code>Map</code>
SWIG
授權(quán)(Authorization)
裝飾器
一切皆對(duì)象
使用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)階

處理異常

我們還沒有談到__exit__方法的這三個(gè)參數(shù):type, valuetraceback。
在第4步和第6步之間,如果發(fā)生異常,Python會(huì)將異常的type,valuetraceback傳遞給__exit__方法。
它讓__exit__方法來決定如何關(guān)閉文件以及是否需要其他步驟。在我們的案例中,我們并沒有注意它們。

那如果我們的文件對(duì)象拋出一個(gè)異常呢?萬一我們嘗試訪問文件對(duì)象的一個(gè)不支持的方法。舉個(gè)例子:

with File('demo.txt', 'w') as opened_file:
    opened_file.undefined_function('Hola!')

我們來列一下,當(dāng)異常發(fā)生時(shí),with語句會(huì)采取哪些步驟。

  1. 它把異常的type,valuetraceback傳遞給__exit__方法
  2. 它讓__exit__方法來處理異常
  3. 如果__exit__返回的是True,那么這個(gè)異常就被優(yōu)雅地處理了。
  4. 如果__exit__返回的是True以外的任何東西,那么這個(gè)異常將被with語句拋出。

在我們的案例中,__exit__方法返回的是None(如果沒有return語句那么方法會(huì)返回None)。因此,with語句拋出了那個(gè)異常。

Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
AttributeError: 'file' object has no attribute 'undefined_function'

我們嘗試下在__exit__方法中處理異常:

class File(object):
    def __init__(self, file_name, method):
        self.file_obj = open(file_name, method)
    def __enter__(self):
        return self.file_obj
    def __exit__(self, type, value, traceback):
        print("Exception has been handled")
        self.file_obj.close()
        return True

with File('demo.txt', 'w') as opened_file:
    opened_file.undefined_function()

# Output: Exception has been handled

我們的__exit__方法返回了True,因此沒有異常會(huì)被with語句拋出。

這還不是實(shí)現(xiàn)上下文管理器的唯一方式。還有一種方式,我們會(huì)在下一節(jié)中一起看看。