except: 不接任何異常屬性 exceptions,表示所有 exceptions 都符合。
except Expection1: 接異常屬性 Exception1,表示符合 Exceptions1。
except(Exception1[, Exception2[,...ExceptionN]]]): 接多個異常屬性,表示符合列出的 Exceptions1, Exceptions2, ...。
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.
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()
[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