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

python错误继承表:

格式:

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 

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

抛出错误:raisedef 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 

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值