笔记-python异常信息输出

笔记-python异常信息输出

 

1.      异常信息输出

python异常捕获使用try-except-else-finally语句;

 

在except 语句中可以使用except as e,然后通过e得到异常信息;

 

  1. str(e): # 返回字符串类型,只给出异常信息,不包括异常信息的类型,如I/O的异常信息。

division by zero

  1. repr(e): #给出较全的异常信息,包括异常信息的类型

ZeroDivisionError('division by zero',)

  1. e.message #信息最为丰富,一般情况下使用这个选项就足够了
  2. traceback# 获取信息最全

 

2.      traceback

 

This module provides a standard interface to extract, format and print stack traces of Python programs. It exactly mimics the behavior of the Python interpreter when it prints a stack trace. This is useful when you want to print stack traces under program control, such as in a “wrapper” around the interpreter.

 

The module uses traceback objects — this is the object type that is stored in the sys.last_traceback variable and returned as the third item from sys.exc_info().

 

比较常用的方法有:

print_exception(etype, value, tb [ ,limit [,file ] ])

 

print_exc([limit [ , file ] ]) # 它是一个print_exception的简写,打印信息

format_exc() # 与print_exc类似,但它返回一个字符串,而不是打印

 

 

案例代码:

import traceback
import sys

class Myex_ValueError(Exception):
    """
    my exception
    """
   
def __init__(self, msg):
        self.message = msg


try:
    a = 5
    b = 5/0
    raise Myex_ValueError('error')
except Exception as e:
    #print(e)
    #print(str(e))
    #print(repr(e))
    #print(e.__class__)
    #print(e.message)
    #traceback.print_exc()
   
print(traceback.format_exc())
    #traceback.print_stack()

 

3.      sys

上面提到了traceback会生成traceback 对象,而这个对象可以通过sys.exc_info()得到。

sys.exc_info()的返回值是一个tuple, (type, value/message, traceback)

这里的type ---- 异常的类型

value/message ---- 异常的信息或者参数

traceback ---- 包含调用栈信息的对象。

 

转载于:https://www.cnblogs.com/wodeboke-y/p/10213537.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值