1.list#异常处理 #1.当条件为假的时候,抛出断言异常:AssertionError #2.尝试访问未知对象,抛出异常AttributeError #3.超出索引抛出异常 IndexError #4.SyntaxError:语法报错 #5.TypeError:运算类型报错 #6.ZeroDivisionError:除数为0报错
list1=[2] list2=[1,2,3,4] assert len(list1)>0#正确 list1.pop() #assert len(list1)>0 #抛出异常AssertionError #list1.f() #AttributeError #list2[4] #IndexError2.#7.try-except语句 try : 检测范围 except Exception[as reason]: 出现异常(Exception)后的处理代码
try: #int('123') f=open('22.txt') print(f.read()) f.close() except OSError as reason: print('文件出错了') except ValueError as reason : print('文件出错了') ##########或者用这一句话也可以#################### except (ValueError, OSError) : print('文件出错了')3. try : 检测范围 except Exception[as reason]: 出现异常(Exception)后的处理代码
finally:
无论如何都要执行的代码