书中对这部分主要讲了三个要点:
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")
本文详细介绍了Python中的异常处理机制,包括try...except...else、raise及try...finally等关键概念,并通过具体实例展示了如何使用这些机制来有效管理和捕获程序运行过程中的各种异常。
9315

被折叠的 条评论
为什么被折叠?



