0

python traceback模块

 2 years ago
source link: https://www.hi-roy.com/posts/python-traceback%E6%A8%A1%E5%9D%97/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

python traceback模块

2013-11-14

如果我们再程序中写出一个会引发异常的代码,比如1/0,就会引发一个异常,程序中止。

Traceback (most recent call last):
  File "trackbacks.py", line 1, in <module>
    1/0
ZeroDivisionError: integer division or modulo by zero
Shell 已返回1

为了程序的健壮性,我们常常加入异常处理。

try:
    1/0
except:
    print "error"

这样,程序就会输出error后正常退出。那么为了能处理异常而又看见异常信息的话就要用到traceback模块了:

import traceback
try:
    1/0
except:
    print "error"
    print traceback.format_exc()
error
Traceback (most recent call last):
  File "trackbacks.py", line 4, in <module>
    1/0
ZeroDivisionError: integer division or modulo by zero

也可以把信息输出到文件中,具体看 http://docs.python.org/2/library/traceback.html

Roy avatar
About Roy
野生程序猿,略懂Python,略懂Golang,略懂云计算,略懂大数据,略懂拳击游泳钓鱼,略懂钢琴吉他摄影。

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK