Exception 參數

  1. 要取得異常發生之參數,可使用以下語法:
    try:
    	You do your operations here;
    	......................
    # 舊語法
    except ExceptionType, Argument:
    # 新語法
    except ExceptionType as Argument:
    	You can print value of Argument here...
    
  2. 範例:列印異常屬性 IOError 的編號,參數變數設為 e。
    pyuser@deyu:~/zzz$ cat try5.py 
    #!/usr/bin/python
    import sys
    
    try:
        fo = open(sys.argv[1], "r")
        data = fo.read()
    except IOError as e:
        print("Error: can\'t read file", sys.argv[1])
        print("Error number =", e.errno)
    else:
        wordlist = data.split()
        print("Word count for", sys.argv[1], "=", len(wordlist))
        fo.close()
    finally:
        print("程式結束")
    
  3. 執行結果:IOError 的錯誤碼為 2。
    pyuser@deyu:~/zzz$ ./try5.py /etc/qwe
    Error: can't read file /etc/qwe
    Error number = 2
    程式結束