无异常捕获
程序遇到异常会中断
print( xxx ) print("---- 完 -----")
得到结果为:
有异常捕获
程序遇到异常会进入异常处理,并继续执行下面程序
try: except NameError as e: 出现错误",e) ")
抓住所有异常
: (xx) Exception as e: ----异常---%s"%e) #输出:----异常---name 'xx' is not defined
捕获多个异常:
方法一:
【except (异常1,异常2) as e:】如果多个异常可以使用一个处理方法时,可使用多异常捕获方法
方法二:
多个异常,使用不同的异常处理,但这样只会进入第一个发生异常处,然后跳出异常捕获
xx=[ ] : print( xxx ) NameError print(xx[1]) IndexError 出现错误1 IndexError as e: 出现错误2 Exception as e: 未知错误")
else和finally的用法
NameError else: 一切正常) finally不管有没有错,我必须执行")
自定义异常:
1 class DongExcep(Exception): 2 def __init__(self,msgxx): 3 self.msgx=msgxx 4 5 实质调用该方法,可以不写也会输出类属性值 6 __str__(self): 7 return 东==>:%s"%(self.msgx) 8 9 : 10 抛出自定义异常 11 raise DongExcep(东小东自定义异常) 12 13 捕获自定义异常 14 except DongExcep as e: # 15 16 17 ")
注意:
缩进错误(IndentationError),不可被捕获