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. ......................
[dywang@dywmac zzz]$ cat except4.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() finally: print "程式結束"
[dywang@dywmac zzz]$ ./except4.py /etc/cde Error: can't read file /etc/cde 程式結束 [dywang@dywmac zzz]$ ./except4.py /etc/resolv.conf Word count for /etc/resolv.conf = 8 程式結束