1 異常的處理
#!/usr/bin/python3
# exceptions.py by Bill Weinman [http://bw.org/]# This is an exercise file from Python 3 Essential Training on lynda.com
# Copyright 2010 The BearHeart Gorup, LLC
def main():
try:
fh = open('sslines.txt') #當文件不存在時
except IOError as e:
print("Could not open the file.come back tommorow",e)
else:
for line in fh: print(line.strip())
if __name__ == "__main__": main()
2 拋出異常
#!/usr/bin/python3
# exceptions.py by Bill Weinman [http://bw.org/]
# This is an exercise file from Python 3 Essential Training on lynda.com
# Copyright 2010 The BearHeart Gorup, LLC
def main():
try:
for line in readFile("han.doc"):
print(line.strip())
except IOError: print('file does not exist')
except ValueError as e:print(e)
def readFile(filename):
if filename.endswith('.txt'):
fh=open(filename)
return fh.readlines()
else:
raise ValueError('File name must end with .txt')
if __name__ == "__main__": main()