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. 範例:無論有無異常發生,最後一定列印「程式結束」。
    pyuser@deyu:~/zzz$ cat try4.py 
    #!/usr/bin/python
    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,最後都印出「程式結束」。
    pyuser@deyu:~/zzz$ ./try4.py /etc/cde
    Error: can't read file /etc/cde
    程式結束
    
  4. 執行結果:參數為可讀取的檔案 /etc/resolv.conf,最後也印出「程式結束」。
    pyuser@deyu:~/zzz$ ./try4.py /etc/resolv.conf 
    Word count for /etc/resolv.conf = 6
    程式結束