V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
推荐学习书目
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 · Feb 3, 2020 · 2278 views
    This topic created in 2280 days ago, the information mentioned may be changed or developed.
    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 replies    2020-02-03 20:42:10 +08:00
    optional
        1
    optional  
       Feb 3, 2020
    继承
    1462326016
        2
    1462326016  
       Feb 3, 2020
    一楼正解
    ```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  
       Feb 3, 2020
    这么写就可以,上边的错误类写多了
    不知道回复里怎么用 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))
    ```
    freemoon
        4
    freemoon  
       Feb 3, 2020
    error.args[0]
    hxse
        5
    hxse  
    OP
       Feb 3, 2020
    @lasuar 多谢, 你这个是最简单的
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2250 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 44ms · UTC 01:16 · PVG 09:16 · LAX 18:16 · JFK 21:16
    ♥ Do have faith in what you're doing.