推荐学习书目
› 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 · 2719 views
    This topic created in 2486 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
    optional
    Feb 3, 2020
    1
    继承
    1462326016
    1462326016
    Feb 3, 2020
    2
    一楼正解
    ```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
    1462326016
    Feb 3, 2020
    3
    这么写就可以,上边的错误类写多了
    不知道回复里怎么用 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
    freemoon
    Feb 3, 2020
    4
    error.args[0]
    hxse
    hxse
    OP
    Feb 3, 2020
    5
    @lasuar 多谢, 你这个是最简单的
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   969 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 19:50 · PVG 03:50 · LAX 11:50 · JFK 14:50
    ♥ Do have faith in what you're doing.