python异常捕获使用try-except-else-finally语句;
在except 语句中可以使用except as e,然后通过e得到异常信息;
division by zero
ZeroDivisionError(‘division by zero‘,)
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()
上面提到了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