1.异常处理
程序在运行的时候,很有可能会出现意想不到的bug,在编写程序时,对可能出现bug的地方进行预处理,当bug出现时,指定执行另一处理方式,来避免程序在运行过程中崩溃。
1.1 异常的几种形式
- 语法错误
- 逻辑错误
1.2 异常的种类
- AttributeError:找不到这个方法
- IOError:输入或者输出异常
- ImportError:导入模块时发生错误
- IndentationError:语法错误
- IndexError:索引错误,比如列表内只有三个数,而索引了第四个数
- KeyError:字典内没有这个键
- NameError:变量名未被赋值
- SyntaxErrot:语法错误
- TypeError:类型错误
- UnboundLocalError:传入了一个调用者不期望的 值
2.异常处理的方法
2.1 if判断式
通过if判断,来对可能出现的错误进行处理,如果xx..则zz。
-
a=input('please input a int') if isinstance(a,int): print('this is int') elif isinstance(a,str): print('this is str') else: print('please input a int333')
if异常处理需要对不同的错误进行估计,针对不同的错误类型分类处理,而且有很多重复代码,当出现多个input的时候,需要有很多个if===》不建议用
2.2 try,except
2.2.1格式:
try: a=input('please input a intt') int(a) b=input('please input a str') except TypeError: print('aaa') #如果try代码块内出现一个异常,异常之后的代码都不会运行
try: pass #被检测的代码块e except 错误类型: pass #如果出现一场则如何处理
2.2.2举例:
try: age=input('please input an int') int(age) print('you are right') except ValueError: print('you have inputed a wrong type')
2.3 异常的作用
2.3.1 多分支
try: a=input('please input an int') int(a) except ValueError: print('this is ValueError') except TypeError: print('this is TypeError')
2.3.2万能异常
try: a=input('please input an int') int(a) except IOError: print('this is IOError') except TypeError: print('this is TypeError') except Exception:#可以接收任何一场并且做出反馈,可以和之前的特定异常进行结合,类似于else print('this is WANNENGYICHANG')
2.3.3 finally
#无论try内代码块是否由异常,都执行 try: a=input('please input an int') int(a) except Exception: print('this is wanneng') finally: print('this is finally')
2.3.4 主动触发异常
try: raise TypeError except TypeError: print('this is typeerror')
2.3.5 自定义异常
class Zidingyi(BaseException):#要继承于基础异常 def __init__(self,msg): self.msg=msg def __str__(self):#用来打印输出 return self.msg try: raise Zidingyi(';hahah我是自定义异常') except Zidingyi as e: print(e)
2.3.6 断言
assert 1==1
如果断言成功了则执行下面的代码。