异常与调试
2018-05-22 本文已影响0人
viean
通过try...except...finally处理异常。
try:
print 'try...'
r = 10 / 0
print 'result:', r
except ValueError, e:
print 'ValueError:', e
except ZeroDivisionError, e:
print 'except:', e
finally:
print 'finally...'
print 'END'
调用
try...
except: integer division or modulo by zero
finally...
END
调用堆栈
出现异常返回时,会打印调用堆栈
# err.py:
def foo(s):
return 10 / int(s)
def bar(s):
return foo(s) * 2
def main():
bar('0')
main()
执行结果:
$ python err.py
Traceback (most recent call last):
File "err.py", line 11, in <module>
main()
File "err.py", line 9, in main
bar('0')
File "err.py", line 6, in bar
return foo(s) * 2
File "err.py", line 3, in foo
return 10 / int(s)
ZeroDivisionError: integer division or modulo by zero
记录错误
# err.py
import logging
def foo(s):
return 10 / int(s)
def bar(s):
return foo(s) * 2
def main():
try:
bar('0')
except StandardError, e:
logging.exception(e)
main()
print 'END'
抛出异常
# err.py
class FooError(StandardError):
pass
def foo(s):
n = int(s)
if n==0:
raise FooError('invalid value: %s' % s)
return 10 / n
raise语句如果不带参数,就会把当前错误原样抛出
# err.py
def foo(s):
n = int(s)
return 10 / n
def bar(s):
try:
return foo(s) * 2
except StandardError, e:
print 'Error!'
raise
def main():
bar('0')
main()
调试
- print打印
- 断言 断言失败,assert语句本身就会抛出AssertionError:
# err.py
def foo(s):
n = int(s)
assert n != 0, 'n is zero!'
return 10 / n
def main():
foo('0')
启动Python解释器时可以用-O参数来关闭assert
- logging 打印日志
- 启动Python的调试器pdb,让程序以单步方式运行
python -m pdb err.py
pdb.set_trace() 设置断点
pycharm IDE也可以设置断点执行