02.29 Python 異常處理中的 esle

前言

們知道,在Python中,我們是用try--excetp--來做異常處理的,但Python 有別於其他語法的是在異常處理中還提供了else的處理場景,是的,你沒看錯,就是在條件判斷if--else-- 中的else,那我們接下來就來看看在異常處理中else有什麼作用。

else 作用場景


<code>>>> def div():...     try:...             x = int(input('firsut num:'))...             y = int(input('second num:'))...             print(x/y)...     except:...             print('error')...     else:...             print('it is ok')...>>> div()firsut num:2second num:12.0it is ok/<code>

1.finally 與try聯合使用 ,不管異常有沒有觸發,都會執行finally 語句塊的內容。

<code>>>> def div():...     try:...             x = int(input('firsut num:'))...             y = int(input('second num:'))...             print(x/y)...     except:...             print('error')...     else:...             print('it is ok')...     finally:...             print('it is finally')...>>> div()firsut num:2second num:12.0it is okit is finally# 出現異常的情況>>> div()firsut num:1second num:0errorit is finally/<code>

從上面的例子可以看出,當沒有捕獲到異常時,else會執行,當捕獲到異常時,else就不會執行,finally不管異常有沒有觸發,都會執行。


分享到:


相關文章: