2011-07-09 87 views
2

Why is else clause needed for try statement in python ? 嘗試...除了......還有v嵌套的嘗試......除了

把它推向深入:

try: 
    f = open('foo', 'r') 
except IOError as e: 
    error_log.write('Unable to open foo : %s\n' % e) 
else: 
    data = f.read() 
    f.close() 

它的角落情況下,通過else clause解決仍然能夠避免發生在我由nested try...except避免需要else? :

try: 
    f = open('foo', 'r') 
    try: 
    data = f.read() 
    f.close() 
    except: 
    pass 
except IOError as e: 
    error_log.write('Unable to open foo : %s\n' % e) 

回答

6

try..except..else可能不需要,但它可能是好的。在這種情況下,在我看來,try..except..else形式明顯更好。

僅僅因爲你可以沒有語法元素,也不會使它無用。 Decorator的語法純粹是語法糖(我認爲最明顯的例子),for循環只是被優化的循環,等等。 try..except..else有一個好地方,我會說這是一個這樣的地方。

此外,這兩個代碼塊是非常相似的。如果f.read()引發異常(磁盤讀取錯誤,文件內部的數據損壞或其他類似問題),第一個將會引發異常,但第二個會失去它,並認爲一切正常。至於我自己,我寧願沿着這些路線的更多的東西,這是短,還是比較容易理解:

try: 
    with open('foo', 'r') as f: 
     data = f.read() 
except IOError as e: 
    error_log.write('Unable to open foo : %s\n' % e) 

(假設你想趕上在file.readfile.close錯誤,我真的不能明白爲什麼你不會。)

+0

並且不能讓代碼工作。我得到無效的語法。 –

+0

@eryksun:啊,是的,忘記了。我剛剛檢查了Python文檔和[With'語句](http://docs.python.org/reference/compound_stmts.html#with)只是說「版本2.5中的新功能」。而沒有提到需要'__future__'導入,所以我想到'除了'''。 Python文檔中的「複合語句」頁面沒有提及它何時被添加......並且我不記得。 –

+0

很高興知道謝謝 –

0

實際上,並不總是需要,你可以簡單地做:

f = None 
try: 
    f = open('foo', 'r') 
except IOError: 
    error_log.write('Unable to open foo\n') 
if f: 
    data = f.read() 
    f.close() 
+0

但你然後調用'None(讀)()'''這引發'AttributeError' –

+0

抱歉修復!我還在編輯。 –

+0

你確定'如果不是f'會起作用嗎?我想這應該是'如果f' –