复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18import traceback print("程序开始执行:") try: print(1/0) except Exception as e: #该方法捕获所有异常 traceback.print_exc() #该处可报出异常的具体位置和原因 a=traceback.format_exc() #将异常存入变量a中 print("不能被零除",e) #也可以用该方法报异常 except ZeroDivisionError as e: #该方法捕获指定异常 print("不能被零除",e)3 else: print("未发生异常") #如果try中未发生异常,会执行else中的内容 finally: print("无论是否有异常,都会执行finally") print("程序执行完成!")
复制代码
1
2
3
4
5
6
7try: for i in range(10): if i==7: raise #该方法可抛出异常 except: print("出现了数字7")
复制代码
1
2
3
4
5
6
7try: for i in range(10): if i==7: raise Exception("抛出了异常") except Exception as e: print(e) #该处也可打印出"抛出了异常"
复制代码
1
2dir(__builtins__) #可查看内置的所有异常
最后
以上就是端庄咖啡最近收集整理的关于python 处理异常的方法,try except traceback,可报出具体的异常信息,捕获指定异常的全部内容,更多相关python内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复