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