exceptions_handle.py
# 異常的處理
# try...except
# 通常的語句在try塊里 錯(cuò)誤處理器放在except塊里
try:
text = input('Enter something --> ')
except EOFError:
print('Why did you do an EOF on me?')
except KeyboardInterrupt:
print('You cancelled the operation.')
else:
print('You entered {}'.format(text))
# 如果 except 后面不指定錯(cuò)誤名稱 那么就是處理所有錯(cuò)誤
# else 將在沒有發(fā)生異常的時(shí)候執(zhí)行
exceptions_raise.py
# 引發(fā)raise異常
# 要提供錯(cuò)誤名或異常名以及要拋出Thrown的對(duì)象
class ShortInputException(Exception):
'''一個(gè)由用戶定義的異常類'''
def __init__(self,length,atleast):
Exception.__init__(self)
self.length = length
self.atleast = atleast
try:
text = input('Enter something --> ')
if len(text) < 3:
raise ShortInputException(len(text),3)
except EOFError:
print('Why did you do an EOF on me?')
except ShortInputException as ex:
print('ShortInputException: The input was ' + '{0} long, excepted at least {1}'.format(ex.length,ex.atleast))
else:
print('No exception was raised.')
exceptions_finally.py
# try ... finally
# 主要是用在文件里面
import sys
import time
f = None
try:
f = open('poem.txt')
while True:
line = f.readline()
if len(line) == 0:
break
print(line,end='')
# 以便print的內(nèi)容可以被立即打印到屏幕上
sys.stdout.flush()
print('Press ctrl+c now')
# 每打印一行后插入兩秒休眠,讓程序運(yùn)行得比較緩慢
time.sleep(2)
except IOError:
print('Could not find file poem.txt')
except KeyboardInterrupt:
print('!! You cancelled the reading from the file.')
finally:
if f: # 這句話記得要
f.close()
print('(Clearning up:Closed the file)')
exceptions_using_with.py
# 在try塊中獲取資源(也就是open) 然后在finally塊中釋放資源(也就是close())
# with語句可以很簡單做到這一模式
with open('opem.txt') as f:
for line in f:
print(line,end='')
# 文件的關(guān)閉交由with ... open來完成
# with 會(huì)獲取open返回的對(duì)象f
# 然后在代碼塊開始之前調(diào)用 f.__enter__函數(shù)
# 在代碼塊結(jié)束之后調(diào)用 f.__exit__函數(shù)