近来编写一个程序,该程序可以在设定时间内,获取指定文件夹更新的文件夹和文件列表,并根据获取到的更新列表,做一些操作。由于所写程序是放在服务器上运行,为了保证程序在运行的过程中,不时不时跳出些异常信息出来吓其他用户,就在程序中添加了异常处理。将网上的资料整理下,试着将sys.exce_info()和traceback搭配一起使用。效果还算不错,以下信息是我当前处理异常的方式,其中type是异常的类型,value是出现异常的原因,traceback则是通过traceback追中到的异常信息,能够定位到造成异常的代码。

2016-11-07 22:07:56
-------------------------------
type: <type 'exceptions.TypeError'>
value: string indices must be integers, not str
traceback: [('文件名', 行号, '函数名', '出现异常的代码行')]

在try...except中,使用下述两行记录异常情况。针对出现异常之后如何程序如何继续之后的工作,则需要看具体要求。

tp,val,td = sys.exc_info()
Log.logerexception(tp,val,td)

具体代码如下

 import os
import time
import traceback
import sys def logerexception(tp,val,td):
etype = str(tp)
evalue = str(val)
etb = traceback.extract_tb(td)
errormsg = "type: " + etype + "\n"
errormsg += "value: " + evalue + "\n"
errormsg += "traceback: " + str(etb) + "\n"
writetofile(errormsg) def writetofile(errormsg):
logfilepath = os.path.abspath('.') + "/log"
if not os.path.exists(logfilepath):
os.mkdir(logfilepath) logfile = time.strftime("%Y%m%d", time.localtime()) + ".txt"
fp = open(logfilepath + "/" + logfile,"a")
ISOTIMEFORMAT= "%Y-%m-%d %X"
happeningtime = time.strftime(ISOTIMEFORMAT, time.localtime())
usermsg = ""
usermsg += happeningtime + "\n-------------------------------\n"
usermsg += errormsg
fp.write(usermsg + "\n")
fp.close()

最新文章

  1. Membership三步曲之进阶篇 - 深入剖析Provider Model
  2. 行内js函数调用
  3. Autodesk 360 Viewer 已经发布到Autodesk 360平台
  4. Python统计脚本行数(fileinput)
  5. Web 使用PostMan提交特殊格式数据
  6. php函数 date() 详细资料
  7. 如何给DropDownList控件设置样式(ASP.NET MVC)
  8. JMeter数据库性能测试
  9. 选择排序(Selection Sort)
  10. cc150:实现一个算法来删除单链表中间的一个结点,仅仅给出指向那个结点的指针
  11. mysql分页pagination
  12. iOS开发之AutoLayout中的Content Hugging Priority和 Content Compression Resistance Priority解析
  13. Micropython 如何用Turnipbit做一个自动浇水装置
  14. Redux 入门教程(二):中间件与异步操作
  15. Infopath 2013 通过UserProfileService读取AD用户信息
  16. 数据库连接池——C3P0
  17. jq 的onchange事件
  18. python selenium判断元素是否存在的问题
  19. php面向对象基础知识点总结
  20. Microsoft Orleans 之 开发人员指南

热门文章

  1. IOS轮播图
  2. android下面使用SurfaceView+ mediaPlayer播放视频
  3. oracle的IMU和ora-01555
  4. 这次是Selenide测试自动发送博客
  5. SSO之CAS单点登录实例演示
  6. AOP报错:Caused by: java.lang.IllegalArgumentException: error at ::0 can&#39;t find referenced pointcut
  7. python 列表排序
  8. 山东省第七届ACM省赛------Fibonacci
  9. Unity四元数小问题整理
  10. github在liunx上的搭建