try-except-else

  1. expect 語法:
    1. except: 不接任何異常屬性 exceptions,表示所有 exceptions 都符合。
    2. except Expection1: 接異常屬性 Exception1,表示符合 Exceptions1。
    3. except(Exception1[, Exception2[,...ExceptionN]]]): 接多個異常屬性,表示符合列出的 Exceptions1, Exceptions2, ...。
  2. try - except - else 語法如下,當 try 執行後,符合 Exception 屬性,執行 expcet 區塊程式,其餘執行 else 區塊程式:
    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.
    
  3. 範例:讀取命令指定的檔案,無法讀取時輸出Error: can't read file filename;成功讀取則列印檔案的字數。
    [dywang@dywmac zzz]$ cat except3.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()
    
  4. 執行結果:/etc/abc 檔案不存在,無法讀取;/etc/issue 共有 11 個字。
    [dywang@dywmac zzz]$ ./except3.py /etc/abc
    Error: can't read file /etc/abc
    [dywang@dywmac zzz]$ ./except3.py /etc/issue
    Word count for /etc/issue = 11
    
    [dywang@dywmac zzz]$ cat /etc/issue
    De-Yu Wang Linux 6.4 release (Taiwan)
    Kernel \r on an \m