捕获异常:try…except…finally
"""
try 捕获异常
"""
try:
print('try...')
r = 10 / int('0')
print('result:', r)
except ValueError as e:
print('valueError:', e)
except ZeroDivisionError as e:
print('ZeroDivisionError:', e)
else:
print('no error ')
finally:
print('finally....')
print('END')
# 不需要在每个可能出错的地方去捕获错误,只要在合适的层次去捕获错误就可以了
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('finall......')
main()
记录错误:logging
"""
记录错误:
1-Python内置的logging模块可以非常容易地记录错误信息
2-程序打印完错误信息后会继续执行,并正常退出
"""
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)
main()
print('END~~~')
抛出错误:raise
"""
抛出错误:
--如果要抛出错误,首先根据需要,可以定义一个错误的class,选择好继承关系,然后,用raise语句抛出一个错误的实例:
"""
class FooError(ValueError):
pass
def foo(s):
n = int(s)
if n == 0:
raise FooError('invalid value: %s' % s)
return 10 / n
foo(0)
另外一种错误处理方式
"""
抛出错误: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!')
raise
bar()