V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
fyyz
V2EX  ›  Python

python 如何优雅地抛出异常

  •  
  •   fyyz · 2015-09-30 13:27:29 +08:00 · 4075 次点击
    这是一个创建于 3130 天前的主题,其中的信息可能已经有所发展或是发生改变。

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

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

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

    第 1 条附言  ·  2015-09-30 14:25:51 +08:00
    恩,我指的就是下面的这个 "^"
    6 条回复    2015-10-03 12:05:37 +08:00
    clino
        1
    clino  
       2015-09-30 13:32:58 +08:00
    我感觉你是想说打印出 traceback 吧?
    chengzhoukun
        2
    chengzhoukun  
       2015-09-30 13:36:37 +08:00
    http://blog.csdn.net/handsomekang/article/details/9373035

    import traceback
    try:
    print a
    except Exception as e:
    traceback.print_exc()
    chengzhoukun
        3
    chengzhoukun  
       2015-09-30 13:40:17 +08:00
    fengjianxinghun
        4
    fengjianxinghun  
       2015-09-30 14:05:40 +08:00
    抛异常和捕获是 2 个事吧。。。
    DiffView
        5
    DiffView  
       2015-10-01 00:55:05 +08:00
    写个 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
        6
    deangl  
       2015-10-03 12:05:37 +08:00 via Android
    logging.exception(e)
    这个?
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3840 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 04:15 · PVG 12:15 · LAX 21:15 · JFK 00:15
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.