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
hxse
V2EX  ›  Python

请问 try/except 有没有办法传递对象, 而不仅仅是字符串

  •  
  •   hxse · 2020-02-03 19:53:55 +08:00 · 1843 次点击
    这是一个创建于 1536 天前的主题,其中的信息可能已经有所发展或是发生改变。
    try:
        raise RuntimeError(["abc"])
    except RuntimeError as error:
        print(error, type(error))
        print(error[0])
    
    ['abc'] <class 'RuntimeError'>
    TypeError: 'RuntimeError' object is not subscriptable
    
    5 条回复    2020-02-03 20:42:10 +08:00
    optional
        1
    optional  
       2020-02-03 19:57:39 +08:00
    继承
    1462326016
        2
    1462326016  
       2020-02-03 20:08:54 +08:00
    一楼正解
    ```Python
    class CustomizeError(BaseException):
    def __init__(self, data):
    self.data = data
    super(CustomizeError, self).__init__()

    def __data__(self):
    return self.data


    try:
    raise CustomizeError([])
    except CustomizeError as e:
    print(e.data, type(e.data))
    ```
    1462326016
        3
    1462326016  
       2020-02-03 20:10:45 +08:00
    这么写就可以,上边的错误类写多了
    不知道回复里怎么用 markdown
    ```python
    class CustomizeError(BaseException):
    def __init__(self, data):
    self.data = data
    super(CustomizeError, self).__init__()


    try:
    raise CustomizeError([11, 2, 3, 3, 4222])
    except CustomizeError as e:
    print(e.data, type(e.data))
    ```
    lasuar
        4
    lasuar  
       2020-02-03 20:26:28 +08:00
    error.args[0]
    hxse
        5
    hxse  
    OP
       2020-02-03 20:42:10 +08:00
    @lasuar 多谢, 你这个是最简单的
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   963 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 20:45 · PVG 04:45 · LAX 13:45 · JFK 16:45
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.