`traceback` 推荐.
(默认 python2)
简单写:
```python
import traceback
try:
raise TypeError("Oups!")
except Exception, err:
try:
raise TypeError("Again !?!")
except:
pass
traceback.print_exc()
```
如果要拿到详细信息:
```python
import traceback
import sys
try:
raise TypeError("Oups!")
except Exception, err:
try:
exc_info = sys.exc_info()
# do you usefull stuff here
# (potentially raising an exception)
try:
raise TypeError("Again !?!")
except:
pass
# end of useful stuff
finally:
# Display the *original* exception
traceback.print_exception(*exc_info)
del exc_info
````
输出结果类似如下:
```python
Traceback (most recent call last):
File "
t.py", line 6, in <module>
raise TypeError("Oups!")
TypeError: Oups!
```
python3 的话, 输出信息会少一些。
```python
import traceback
try:
raise TypeError("Oups!")
except Exception as err:
try:
raise TypeError("Again !?!")
except:
pass
traceback.print_tb(err.__traceback__)
```
输出大致如下:
```
File "
e3.py", line 4, in <module>
raise TypeError("Oups!")
```
关键是还是去看官方文档 traceback 模块:
python2.7:
https://docs.python.org/2/library/traceback.htmlpython3.6:
https://docs.python.org/3/library/traceback.html我的经验来自: [stackoverflow 链接](
https://stackoverflow.com/questions/3702675/how-to-print-the-full-traceback-without-halting-the-program)