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. finally: This would always be executed. ......................
pyuser@deyu:~/zzz$ cat try4.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()
finally:
print("程式結束")
pyuser@deyu:~/zzz$ ./try4.py /etc/cde Error: can't read file /etc/cde 程式結束
pyuser@deyu:~/zzz$ ./try4.py /etc/resolv.conf Word count for /etc/resolv.conf = 6 程式結束