python错误继承表:
10余年的蓝山网站建设经验,针对设计、前端、开发、售后、文案、推广等六对一服务,响应快,48小时及时工作处理。全网整合营销推广的优势是能够根据用户设备显示端的尺寸不同,自动调整蓝山建站的显示方式,使网站能够适用不同显示终端,在浏览器中调整网站的宽度,无论在任何一种浏览器上浏览网站,都能展现优雅布局与设计,从而大程度地提升浏览体验。创新互联建站从事“蓝山网站设计”,“蓝山网站推广”以来,每个客户项目都认真落实执行。
https://docs.python.org/3/library/exceptions.html#exception-hierarchy
格式:
def 函数():
try:
内容 ###正确输出
except 错误表 in e:
输出内容 ###错误输出
finally:
输出内容 ##必定输出
print('END') ##必定输出
#!/usr/bin/python # -*- coding: utf-8 -*- def foo(s): return 10 / int(s) def bar(s): return foo(s) * 2 def main(): try: bar('0') except Exception as e: print('Error:', e) finally: print('finally...') main()
运行结果:
('Error:', ZeroDivisionError('integer division or modulo by zero',)) finally...
a.面对函数层层调用,try...except能捕捉得到。
b.类的子类错误也能捕捉得到,如捕捉ValueError错误,顺便也会把UnicodeError也捕捉了
+-- ValueError | +-- UnicodeError | +-- UnicodeDecodeError | +-- UnicodeEncodeError | +-- UnicodeTranslateError
记录错误到日志文件:
#!/usr/bin/python # -*- coding: utf-8 -*- import logging ###########记得导入模块 def foo(s): return 10 / int(s) def bar(s): return foo(s) * 2 def main(): try: bar('0') except Exception as e: logging.exception(e) #########模块函数使用 print ('haha') main() print ('END')
运行结果:
haha END ERROR:root:division by zero Traceback (most recent call last): File "/usercode/file.py", line 14, in main bar('0') File "/usercode/file.py", line 10, in bar return foo(s) * 2 File "/usercode/file.py", line 7, in foo return 10 / int(s) ZeroDivisionError: division by zero
当不用错误调试时,普通的程序出错会调用栈Traceback提示错误
def foo(s): return 10 / int(s) def bar(s): return foo(s) * 2 def main(): bar('0') main()
运行结果:
Traceback (most recent call last): File "/usercode/file.py", line 13, in <module> main() File "/usercode/file.py", line 11, in main bar('0') File "/usercode/file.py", line 8, in bar return foo(s) * 2 File "/usercode/file.py", line 5, in foo return 10 / int(s) ZeroDivisionError: integer division or modulo by zero
抛出错误:raise
def foo(s): n = int(s) if n==0: raise ValueError('invalid value: %s' % s) return 10 / n def bar(): try: foo('0') except ValueError as e: print('ValueError!', e) raise bar()
运行结果:
('ValueError!', ValueError('invalid value: 0',)) Traceback (most recent call last): File "/usercode/file.py", line 17, in <module> bar() File "/usercode/file.py", line 12, in bar foo('0') File "/usercode/file.py", line 7, in foo raise ValueError('invalid value: %s' % s) ValueError: invalid value: 0
文章标题:python错误处理:try..except..finally/logging/raise
链接分享:https://www.cdcxhl.com/article46/gisdeg.html
成都网站建设公司_创新互联,为您提供网站设计、Google、手机网站建设、品牌网站制作、自适应网站、静态网站
声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联