try: #代码块,逻辑 inp=input("序号:") i=int(inp) except Exception as e: #e是一个Exception的对象,里面封装了错误信息 #错误时执行 i=1 print(e) # invalid literal for int() with base 10: 'w' print(i)
异常有多种类型数据库
try: li=[1,2,3] li[999] except IndexError as e: print("IndexError:",e)
try: int("dhj") #若是ValueError不能捕获,就会报错 li1=[1,2,3] #一旦出现错误,try后面的代码就再也不执行了 li1[999] except ValueError as e: print("ValueError:",e) except IndexError as e: print("IndexError",e) except Exception as e: print("Exception:",e) else: print("ok!") #前面都没错,执行else finally: print("go on ……") #无论出不出错,都要执行finally # IndexError,ValueError都是Exception的子类 #日志分类时候,须要对细分的错误放在前面,Exception放在最后
主动抛出异常ide
#主动抛出异常 try: #主动触发异常 raise Exception("异常123") #建立了一个Exception()对象 except Exception as e: print(e) # 异常123
日志实例日志
def db(): return False def index(): try: rh="hgd" rh=int(rh) result=db() if not result: raise Exception("数据库处理错误") except Exception as e: str_error=str(e) print(str_error) f=open("log.txt","a",encoding="utf-8") f.write(str_error) f.close() index()
自定义异常code
#自定义异常 class olderror(Exception): def __init__(self,msg): self.message=msg def __str__(self): return self.message a=olderror("ojj") print(a) # ojj try: raise olderror("HEHE") except olderror as e: print(e) # HEHE
断言对象
# assert 断言,条件成立,继续执行,条件不成立,报错,不能日后执行 # assert 条件 print(23) assert 1==2 print(456)