温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

python 错误处理:try..except..finally / logging / raise

发布时间:2020-07-24 03:44:52 来源:网络 阅读:2653 作者:虎皮喵的喵 栏目:编程语言

python错误继承表:

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



向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI