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;成功讀取則列印檔案的字數。
    pyuser@deyu:~/zzz$ cat try3.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()
    
  4. 執行結果:參數 /etc/abc,因檔案不存在,回應無法讀取檔案。
    pyuser@deyu:~/zzz$ ./try3.py /etc/abc
    Error: can't read file /etc/abc
    
  5. 執行結果:參數 /etc/issue,回應共有 6 個字。
    pyuser@deyu:~/zzz$ ./try3.py /etc/issue
    Word count for /etc/issue = 6
    
  6. 查看檔案 /etc/issue。
    pyuser@deyu:~/zzz$ cat /etc/issue
    \S
    Kernel \r on an \m