推荐学习书目
› 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
yujianwjj
V2EX  ›  Python

Python 自定义异常的疑问?

  •  
  •   yujianwjj · Nov 1, 2022 · 3044 views
    This topic created in 1463 days ago, the information mentioned may be changed or developed.

    之前一直写 go ,遇到错误就直接 return err 。现在写 python ,突然不知道怎么处理异常了。

    比如封装一个函数,该函数内调用一个外部接口,接口的返回值不是我期望的内容,这个时候 raise 一个什么样的异常比较好?

    另外请教下,在 Python 中,一般抛出异常有什么最佳实践吗?

    6 replies  •  2022-11-05 14:49:21 +08:00
    krixaar
    krixaar
    Nov 1, 2022
    2
    个人习惯扔个 ValueError(f'什么破接口你看看传的啥破玩意:{result}') 出来,按照文档:
    exception ValueError
    当操作或函数接收到具有正确类型但值不适合的参数,并且情况不能用更精确的异常例如 IndexError 来描述时将被引发。
    https://docs.python.org/zh-cn/3/library/exceptions.html#ValueError
    joApioVVx4M4X6Rf
    joApioVVx4M4X6Rf
    Nov 1, 2022
    3
    接口的话,属于业务上的异常了,最好自己继承一个异常类,最外层 try: except 。
    Trim21
    Trim21
    Nov 1, 2022 via Android
    4
    处理方法一样啊,go 导出的一个 Err 变量对应 python 里面一个异常的类型。go 里面的 errors.Is/errors.As 到了 python 里面就是用 try except/isinstance

    go 里面收到 err 直接 return err 其实就相当于 python 里面不写 try catch 。
    guanzhangzhang
    guanzhangzhang
    Nov 5, 2022
    5
    终于看到和我一样的老哥了,go 的 return err 给上层,然后上层可以打印日志,很多 golang 的项目一看报错基本知道问题范围。然后工作会写些 python ,py 这块的错误处理把我整不会了,还要 try case 每种 err 感觉好麻烦
    guanzhangzhang
    guanzhangzhang
    Nov 5, 2022
    6
    https://www.zlovezl.cn/articles/function-returning-tips/ 我刚看了下这个里的 3. 抛出异常,而不是返回结果与错误 似乎能解答你的疑问
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   5677 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 108ms · UTC 03:08 · PVG 11:08 · LAX 19:08 · JFK 22:08
    ♥ Do have faith in what you're doing.