1. 直接打印错误

  1. try:
  2. # your code
  3. except KeyboardInterrupt:
  4. print("quit")
  5. except Exception as ex:
  6. print("出现如下异常%s"%ex)
  7. try:
  8. 2/0
  9. except Exception as e:
  10. print(e)
  11. # division by zero

2.用traceback模块打印

上述结果看不到具体错误的信息,如行数啥的,不方便调试的时候定位,因此也可以用traceback模块,方便调试

  1. import traceback
  2. try:
  3. 2/0
  4. except Exception as e:
  5. traceback.print_exc()
  6. Traceback (most recent call last):
  7. File "c:\Users\Administrator\Desktop\test1.py", line 3, in <module>
  8. 2/0
  9. ZeroDivisionError: division by zero

ps:上述traceback.print_exc()是直接打印错误
还可以用traceback.format_exc()返回字符串,可将错误信息保存在文档日志中
可以说traceback.print_exc()等同于print traceback.format_exc()