异常处理
python中的异常处理使用try…except…else语句,形式如下:
try:
语句块
except ERROR1:
语句块
except ERROR2:
语句块
...
else
自定义异常类型
通过定义Exception类(或BasException)的子类来自己定义用户异常类型,使用raise语句来抛出异常
示例如下
class UserException(Exception):
def __init__(self,length,adjust):
Exception.__init__(self)
self.length =length
self.doc = adjust
try:
text = input('Enter something --> ')
if len(text) < 3:
raise UserException(len(text), 3)
# 抛出异常对象,其他工作能在此处继续正常运行
except UserException as ex:
# except语句接收类对象,并记为ex,类似于实参与形参的区别,后续通过ex引用该对象
print(('ShortInputException: The input was ' +\
'{0} long, expected at least {1}')\
.format(ex.length, ex.doc))
else:
print('No exception was raised.')
finally语句
如果希望无论有没有异常抛出都执行某些操作,则可以在最后添加finally语句块,示例如下:
class UserException(BaseException):
def __init__(self,length,adjust):
BaseException.__init__(self)
self.length =length
self.doc = adjust
import sys
import time
f = None
try:
f = open("poem.txt")
while True:
line = f.readline()
if len(line) == 0:
break
print(line, end='')
sys.stdout.flush()
text = input('Enter something --> ')
if len(text) < 3:
raise UserException(len(text), 3)
# 为了确保程序能运行一段时间
time.sleep(2)
except IOError:
print("Could not find file poem.txt")
except UserException as ex:
print(('ShortInputException: The input was ' +\
'{0} long, expected at least {1}')\
.format(ex.length, ex.doc))
else:
print('successfully finished')
finally:
if f:
f.close()
print("(Cleaning up: Closed the file)")
with语句
上述例子中的finally语句块主要用来保证文件打开后能够被正确的关闭,在python中提供with语句可以直接实现这一功能,即with 语句可以保证诸如文件之类的对象在使用完之后一定会正确的执行他的清理方法:。
示例:
with open("myfile.txt") as f:
for line in f:
print(line, end="")
等价于
try:
f = open("myfile.txt")
for line in f
print(line, end="")
finally:
f.close()