推荐学习书目
› 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 · 5036 views
    This topic created in 4027 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
        1
    clino  
       Sep 30, 2015
    我感觉你是想说打印出 traceback 吧?
    chengzhoukun
        2
    chengzhoukun  
       Sep 30, 2015
    http://blog.csdn.net/handsomekang/article/details/9373035

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