Python之异常处理
当一个程序运行时报错,可以通过Python异常处理机制忽略错误或者以友好的方式提示错误
vim day8-2.py
1 2 3 4 5 6 7 8 | #!/usr/bin/python # -*- coding:utf-8 -*- try : input = raw_input () data = int ( input ) print data except Exception,e: print '请输入数字' |
错误有很多种可以定义对于某一种异常进行处理
1 2 3 4 5 6 7 8 9 10 11 12 | #!/usr/bin/python # -*- coding:utf-8 -*- try : dic = { 'k1' , 'v1' } dic[ 'ddd' ] except IndexError,e: #如果出现IndexError错误执行下面的 print 'errot' ,e except KeyError,e: #如果出现KeyError错误执行下面的 print e except TypeError,e: #如果出现KeyError错误执行下面的 print e #如果以上错误均为出现则报错 |
PS:可以在最后加 except Exception,e:处理所有无法预测到的错误
以上的捕获异常代码异常,还有一种异常是主动触发异常,如果是自己想让代码出现异常
创建一个模块helper.py提供了很多公共的组件
1 2 3 4 5 6 7 8 9 10 11 | #!/usr/bin/python # -*- coding:utf-8 -*- def f1(): return False def f2(): pass def f3(): pass |
vim day8-4.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | #!/usr/bin/python # -*- coding:utf-8 -*- import helper if __name__ = = '__main__' : try : n = "1" n = int (n) ret = helper.f1() if ret: print 'chenggong' else : # print 'shibai' raise Exception( 'error' ) except Exception,e: print "出现错误" print e #记录日志,e |
在里面调用另外的模块如果另外的模块执行错误则主动触发一个异常(这里通过f1返回False强行触发错误)并且封装到e里面,然后打印出来
自定义异常
vim day8-5.py
1 2 3 4 5 6 7 8 | class AlexError(Exception): def __str__( self ): return 'alex error' try : raise AlexError() except Exception,e: print e |
以上自定义异常输出一直不变修改代码动态更新异常
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | #!/usr/bin/python # -*- coding:utf-8 -*- class AlexError(Exception): #定义类继承Exception def __init__( self ,msg = None ): self .message = msg def __str__( self ): if self .message: return self .message else : return 'alex error' try : raise AlexError( 'dasdkj' ) except Exception,e: print e |
异常及为传递的字符串
不传递参数返回错误为alex error
异常处理之断言
满足条件则执行
assert 1==1
assert 1==2
分类:
Python学习
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!