推荐学习书目
› 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 · Sep 30, 2015 · 5129 views
    This topic created in 4057 days ago, the information mentioned may be changed or developed.

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

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

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

    Supplement 1  ·  Sep 30, 2015
    恩,我指的就是下面的这个 "^"
    6 replies  •  2015-10-03 12:05:37 +08:00
    clino
    clino
    Sep 30, 2015
    1
    我感觉你是想说打印出 traceback 吧?
    chengzhoukun
    chengzhoukun
    Sep 30, 2015
    2
    http://blog.csdn.net/handsomekang/article/details/9373035

    import traceback
    try:
    print a
    except Exception as e:
    traceback.print_exc()
    chengzhoukun
    chengzhoukun
    Sep 30, 2015
    3
    fengjianxinghun
    fengjianxinghun
    Sep 30, 2015
    4
    抛异常和捕获是 2 个事吧。。。
    DiffView
    DiffView
    Oct 1, 2015
    5
    写个 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
    deangl
    Oct 3, 2015 via Android
    6
    logging.exception(e)
    这个?
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   4153 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 32ms · UTC 01:55 · PVG 09:55 · LAX 17:55 · JFK 20:55
    ♥ Do have faith in what you're doing.