try-finally

  1. finally 關鍵字放在 try 後,中間可以有 except 及 else,不論有沒有異常發生,一定會執行 finally 區塊的程式碼。
    try:
    	You do your operations here;
    	......................
    except Exception:
    	If there is Exception, then execute this block.
    else:
    	If there is no exception then execute this block.
    finally:
    	This would always be executed.
    	......................
    
  2. 範例:無論有無異常發生,最後一定列印「程式結束」。
    [dywang@dywmac zzz]$ cat except4.py 
    #!/usr/bin/python
    # coding: utf-8
    import sys
    
    try:
    	fo = open(sys.argv[1], "r")
    	data = fo.read()
    except IOError:
    	print "Error: can\'t read file", sys.argv[1]
    else:
    	wordlist = data.split()
    	print "Word count for", sys.argv[1], "=", len(wordlist)
    	fo.close()
    finally:
    	print "程式結束"
    
  3. 執行結果:無論不存在的檔案 /etc/cde 或可讀取的檔案 /etc/resolv.conf,最後都印出「程式結束」。
    [dywang@dywmac zzz]$ ./except4.py /etc/cde
    Error: can't read file /etc/cde
    程式結束
    [dywang@dywmac zzz]$ ./except4.py /etc/resolv.conf 
    Word count for /etc/resolv.conf = 8
    程式結束