书中对这部分主要讲了三个要点:
1、try……except……else;
2、raise;
3、try……finally;
try……except:
try:
block
#as e1可以不写
#当要输出异常时,可以写print("e1")
except Exception as e1:
block
……
else:
block
将所有可能出现错误或者发生异常的statements写在try-block中。在执行程序过程中,先执行try-block,若发生异常,在except-block中处理这些异常;如果未出现异常,执行else部分的语句。
其中,else-block可加可不加。Exception可以写成具体的异常(raise部分的例子),如:EOFError,KeyboardInterrupt……
raise:
raise需要
class ShortInputException(Exception):
def __init__(self,length,atleast):
Exception.__init__(self)
self.length = length
self.atleast = atleast
try:
text = input("enter somthing: ")
if len(text) < 3:
raise ShortInputException(len(text),3)
except EOFError:
print("eoferror")
except ShortInputException as e:
print("shortinputexception: input length is {}, however the least length is {}".format(e.length,e.atleast))
else:
print("no exception")