Fork me on GitHub

TraceBack

#!/usr/bin/env python3
# _*_ coding:utf-8 _*_
# ========================================================
# Module         :  ExceotionTraceBack
# Author         :  luting
# Create Date    :  2018/6/7
# Amended by     :  luting
# Amend History  :  2018/6/7
# =======================================================
import traceback


# 捕捉异常基本操作
try:
    with open('xxx.txt', 'r') as file:
        for line in file:
            print(line)
except Exception as error:
    print(error)


# 使用traceback -> 能清楚具体哪一行代码出错
try:
    with open('xxx.txt', 'r') as file:
        for line in file:
            print(line)
except Exception:
    # print_exc 直接打印
    traceback.print_exc(file=open('error.txt', 'w+'))

try:
    with open('xxx.txt', 'r') as file:
        for line in file:
            print(line)
except Exception:
    # format_exc 返回字符串
    print(traceback.format_exc())

 

posted @ 2018-06-07 10:47  未凉残念浮生若梦  阅读(272)  评论(0编辑  收藏  举报