python 如何优雅地抛出异常

2015 年 9 月 30 日
 fyyz

如果我执行错误的代码, python 原生的抛出异常能处理得非常优雅:

>>> print a
File "<stdin>", line 1
 print a
       ^
SyntaxError: Missing parentheses in call to 'print'

自己写的代码如何才能这么优雅地抛出异常呢?

4782 次点击
所在节点    Python
6 条回复
clino
2015 年 9 月 30 日
我感觉你是想说打印出 traceback 吧?
chengzhoukun
2015 年 9 月 30 日
http://blog.csdn.net/handsomekang/article/details/9373035

import traceback
try:
print a
except Exception as e:
traceback.print_exc()
chengzhoukun
2015 年 9 月 30 日
fengjianxinghun
2015 年 9 月 30 日
抛异常和捕获是 2 个事吧。。。
DiffView
2015 年 10 月 1 日
写个 log 模块比如 https://www.fancycoding.com/custom-python-log-module/
然后
try:
momoda
except Exception as e:
LogC(self, traceback.format_exc())

得到
2014-12-06 15:10:56,818 - C - CRITICAL - you can't momoda me
deangl
2015 年 10 月 3 日
logging.exception(e)
这个?

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://study.congcong.us/t/224777

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX