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;成功讀取則列印檔案的字數。
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()
pyuser@deyu:~/zzz$ ./try3.py /etc/abc Error: can't read file /etc/abc
pyuser@deyu:~/zzz$ ./try3.py /etc/issue Word count for /etc/issue = 6
pyuser@deyu:~/zzz$ cat /etc/issue \S Kernel \r on an \m